讓我舉例說明。
輸入:
我有一個二維陣列:
arr = [['13.12', 'www.randomLinkHere.com'], ['13.6', 'www.randomLinkHere.com'], ['13.2', 'www.randomLinkHere.com']]
我想根據第一列 => arr[i][0] 對它們進行排序。
但是當我使用簡單的比較函式 (a - b) 對它們進行排序時,它會回傳如下內容:
輸出:[['13.12', 'www.randomLinkHere.com'], ['13.2', 'www.randomLinkHere.com'], ['13.6', 'www.randomLinkHere.com']]
但預期的結果必須是:
預期的'版本排序':[['13.2','www.randomLinkHere.com'],['13.6','www.randomLinkHere.com'],['13.12','www.randomLinkHere.com']]
就像它是一個物件。
參考:預期結果作為參考
uj5u.com熱心網友回復:
const arr = [
["13.12", "www.randomLinkHere.com"],
["13.6", "www.randomLinkHere.com"],
["13.2", "www.randomLinkHere.com"],
];
const sortedArr = arr.sort(
(a, b) =>
a[0].split(".").reduce((acc, val) => acc parseFloat(val) * 100, 0) -
b[0].split(".").reduce((acc, val) => acc parseFloat(val) * 100, 0)
);
console.log(sortedArr);
uj5u.com熱心網友回復:
const arr = [
['13.12', 'www.randomLinkHere.com'],
['13.6', 'www.randomLinkHere.com'],
['13.2', 'www.randomLinkHere.com'],
];
const sortArr = (arr) => {
return arr.sort((a, b) => {
if ( a[0] > b[0]) return 1;
return 0;
}).reverse();
};
console.log(sortArr(arr));
uj5u.com熱心網友回復:
在這里你期待一些不尋常的東西,因為 13.2 總是大于 13.12,你不能將數字 13.2 視為 13.02。
考慮數字,您可以嘗試下面的代碼。
const arr = [['13.12', 'www.randomLinkHere.com'], ['13.6', 'www.randomLinkHere.com'], ['13.2', 'www.randomLinkHere.com']]
arr.sort((ele1, ele2) => {
const a = Number(ele1[0]);
const b = Number(ele2[0]);
return a < b ? -1 : b < a ? 1 : 0 ;
});
或者,如果您想將 13.2 視為 13.02,請嘗試以下一項
const arr = [['13.12', 'www.randomLinkHere.com'], ['13.6', 'www.randomLinkHere.com'], ['13.2', 'www.randomLinkHere.com']]
arr.sort((ele1, ele2) => {
const a = ele1[0].split('.');
const b = ele2[0].split('.');
a[1] = a[1] < 10 ? '0' a[1] : a[1];
b[1] = b[1] < 10 ? '0' b[1] : b[1];
const fineNumber1 = a.join('.');
const fineNumber2 = b.join('.');
return a < b ? -1 : b < a ? 1 : 0 ;
})
console.log(arr);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/460470.html
標籤:javascript 数组 排序 多维数组
下一篇:從三個陣列中獲取第一個元素并將它們放入自己的陣列中,然后在javascript中對第二個元素執行相同操作,依此類推
