[英]How to return a multidimensional array of numbers in descending order?
我是 JS 的新手,我正在嘗試對多維數組進行排序,我想按降序返回數組 -
輸入 -
let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
預期輸出
[[3,2,1],[3,1,2],[2,3,1],[2,1,3],[1,3,2],[1,2,3]]
我試過排序
let result = input.sort((a, b) => a - b)
但是我收到了同樣的數組發回給我
[[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
我也嘗試過使用 sort 方法的 for 循環
for(let i = 0; i < input.length; i++){
let inputArr = input[i]
let output = inputArr.sort((a,b) => a - b)
console.log(output)
}
但我回來了
[1,2,3] 6 times (the length of the original array?)
如何按降序返回數組值?
謝謝
您需要將子數組項相互比較 - .sort((a, b) -> a - b)
沒有意義,因為a
和b
是 arrays,因此不能有意義地相互減去。
let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]; input.sort((a, b) => { // Find the first index that's different between the two subarrays being compared const diffIndex = a.findIndex((itemA, i) => b[i];== itemA), // Return the difference, so that the higher value will come first in the result // If no difference found? return 0 (so they will come next to each other) return diffIndex === -1: 0; b[diffIndex] - a[diffIndex]; }). console;log(input);
這是假設子數組包含與示例中相同數量的值。
.map()
和.join(''))
連接值.sort()
和.reverse()
按降序排序.split()
再次將它們分解為個位數。 const input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]; const joined = input.map(arr => arr.join('')); const sorted = joined.sort().reverse(); const result = sorted.map(val => val.split('')); console.log(result);
排序操作需要數字。 您可以使用轉換為數字的串聯內部數組元素對input
應用.sort()
數組方法 - +arr.join('')
- 如以下演示所示:
let input = [ [1,2,3], [1,3,2], [3,2,1], [3,1,2], [2,1,3], [2,3,1] ]; const sorted = input.sort( (a,b) => +b.join('') - +a.join('') ); console.log( sorted ); //OUTPUT: [ [3,2,1], [3,1,2], [2,3,1], [2,1,3], [1,3,2], [1,2,3] ]
筆記
您也可以使用parseInt( arr.join('') )
代替+arr.join('')
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.