使用 JavaScript reduce 函数对数组进行排序 - 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
// without using the array sort function
// without using any kind of conventional loops
// 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 ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP