在JavaScript中不使用sort()对数组进行排序
我们需要编写一个包含数字数组的JavaScript函数。
该函数应该使用Array.prototype.sort()方法对数组进行排序,但是,在这里,我们需要使用Array.prototype.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 ]
热门推荐
10 高一祝福语简短 励志
11 立秋节气简短祝福语
12 简短公司周年祝福语大全
13 中考感言简短祝福语大全
14 体育老师简短祝福语
15 干杯生日祝福语简短独特
16 特别简短的祝福语老师
17 朋友坐车走了祝福语简短
18 给英雄的祝福语简短