使用 JavaScript 的 Reduce 函数对数组进行排序 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/31 19:24:17
我们需要编写一个 JavaScript 函数,该函数接受一个数字数组。该函数应使用 Array.prototype.sort() 方法对数组进行排序。我们需要使用 Array.prototype.reduce() 方法对数组进行排序。
假设以下是我们的数组 −
const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];
示例
以下是代码 −
// 我们将对这个数组进行排序,但
// 不使用数组排序函数
// 不使用任何类型的常规循环
// 使用 ES6 函数 Reduce()
const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];
const sortWithReduce = arr => {
return arr.reduce((acc, val) => {
let ind = 0;
while(ind < arr.length && val < arr[ind]){
ind++;
}
acc.splice(ind, 0, val);
return acc;
}, []);
};
console.log(sortWithReduce(arr));
输出
这将在控制台中产生以下输出 −
[ 98, 57, 89, 37, 34, 5, 56, 4, 3 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

