在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 ]
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下