在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 妈妈生日祝福语简短励志