使用JavaScript归约功能对数组进行排序-JavaScript
我们需要编写一个包含数字数组的JavaScript函数。该函数应使用Array.prototype.sort()方法对数组进行排序。我们需要使用Array.prototype.reduce()方法对数组进行排序。
假设以下是我们的数组-
const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];
示例
以下是代码-
// we will sort this array but
//不使用数组排序功能
//不使用任何常规循环
// using the ES6 function 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 红包祝福语简短10字
18 周六早晨祝福语简短