我有一個看起來像這樣的陣列
['NAME', 5, '2. Defender', 'FALSE', 'TRUE', 'FALSE', 'undefined']
['NAME', 5, '4. Forward', 'TRUE', 'TRUE', 'FALSE', 'undefined']
['NAME', 5, '2. Defender', 'FALSE', 'TRUE', 'FALSE', 'undefined']
['NAME', 4, '4. Forward', 'FALSE', 'TRUE', 'FALSE', 'undefined']
['NAME', 3, '5. Midfielder', 'FALSE', 'FALSE', 'FALSE', 'undefined']
我正在參考此頁面以了解如何對其進行排序,這就是我所擁有的:
array.sort(
function(a, b) {
if (a[1] === b[1]) {
// Price is only important when cities are the same
return b[2] - a[2];
}
return a[1] < b[1] ? 1 : -1;
});
它僅按[1]值排序,不會按次要[2]值排序。我認為我的陣列可能有問題,但是當我先將事物切換為排序依據時[2],它會按該值排序。雖然目標是先排序[1],然后再排序[2]。
uj5u.com熱心網友回復:
第三個陣列元素 [2] 是一個不能通過減法比較的字串。.localeCompare改為使用
array.sort((a, b) => a[1] !== b[1] ? a[1] - b[1] : a[2].localeCompare(b[2]))
uj5u.com熱心網友回復:
您正在嘗試使用兩個字串('2. Defender'vs. '4. Forward')執行數學運算。
您可以嵌套您為a[1]vs.所做的相同比較b[1],如下所示:
顯示代碼片段
let array = [
['ONE1', 5, '2. Defender', 'FALSE', 'TRUE', 'FALSE', 'undefined'],
['TWO2', 5, '4. Forward', 'TRUE', 'TRUE', 'FALSE', 'undefined'],
['THR3', 5, '2. Defender', 'TRUE', 'TRUE', 'FALSE', 'undefined'],
['FOR4', 4, '4. Forward', 'FALSE', 'TRUE', 'FALSE', 'undefined'],
['FIV5', 3, '5. Midfielder', 'FALSE', 'FALSE', 'FALSE', 'undefined']
]
array.sort(function(a, b) {
if (a[1] === b[1]) {
// Price is only important when cities are the same
if (a[2] === b[2]) {
//return 0;
/*
or nest another comparison here and as many times as needed
within each child `a[n]===b[n]` block
*/
if (a[3] === b[3]) {
return 0; // or compare yet another col
}
return a[3] < b[3] ? 1 : -1;
}
return a[2] < b[2] ? 1 : -1;
}
return a[1] < b[1] ? 1 : -1;
})
array.forEach((p) => {
console.log(p[0])
})
否則,您需要獲取這些字串的整數值才能進行數學運算。您可以parseInt()根據每個排序列的邏輯使用或分配顯式值,如下所示:
let array = [
['ONE1', 5, '2. Defender', 'FALSE', 'TRUE', 'FALSE', 'undefined'],
['TWO2', 5, '4. Forward', 'TRUE', 'TRUE', 'FALSE', 'undefined'],
['THR3', 5, '2. Defender', 'TRUE', 'TRUE', 'FALSE', 'undefined'],
['FOR4', 4, '4. Forward', 'FALSE', 'TRUE', 'FALSE', 'undefined'],
['FIV5', 3, '5. Midfielder', 'FALSE', 'FALSE', 'FALSE', 'undefined']
]
array.sort(function(a, b) {
if (a[1] === b[1]) {
// Price is only important when cities are the same
let c = parseInt(a[2]);
let d = parseInt(b[2]);
if (c === d) {
// the string 'TRUE' before 'FALSE', '' or null
let e = (a[3] === 'TRUE') ? 1 : 0;
let f = (b[3] === 'TRUE') ? 1 : 0;
return f - e;
}
return d - c;
}
return a[1] < b[1] ? 1 : -1;
})
array.forEach((p) => {
console.log(...p)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483294.html
標籤:javascript 数组 排序
上一篇:從物件中獲取所有唯一值并將它們分配到正確鍵下的陣列中
下一篇:使用Enter鍵使復選框起作用
