使用 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