所以基本上,我有這個陣列
array = [[1,0],[2,1],[0,3],[3,2]]
有什么快速的方法可以將陣列轉換成這樣
array = [[0,3],[3,2],[2,1],[1,0]]
我想要的是新陣列的第一個元素在嵌套陣列的第一個位置始終包含 0。這很容易,因為sort()函式就是這樣做的;困難的部分是像上面那樣訂購新的陣列。
用最簡單的術語來說,我希望嵌套陣列是“連接的”:看看3第一個嵌套陣列的第一個如何與另一個嵌套陣列匹配3,依此類推。
隨時留下任何評論,以便我可以嘗試更好地解釋問題。
uj5u.com熱心網友回復:
對于您提供的示例,最簡單的解決方案是按每個內部陣列的第二個元素對二維陣列進行排序,如下所示:
let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);
這樣,您可以根據內部陣列中的元素使用 sort 方法對陣列進行排序。
let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);
console.log(array);
uj5u.com熱心網友回復:
您可以將物件作為參考并通過獲取鏈接項來重建陣列。
const
getItems = (reference, value) => {
const a = reference[value];
return a ? [a, ...(a[1] === 0 ? [] : getItems(reference, a[1]))] : [];
},
array = [[1, 0], [2, 1], [0, 3], [3, 2]],
reference = array.reduce((r, a) => (r[a[0]] = a, r), {}),
result = getItems(reference, 0);
console.log(result);
uj5u.com熱心網友回復:
看看這個方法:
const array = [[1,0],[2,1],[0,3],[3,2]];
const result = [...array];
// Put the subarray with the zero element first
// You can use the sort() function but I guess this method
// performs better in terms of time
for (let i = 0; i < result.length; i) {
if (result[i][0] === 0) {
result.unshift(...result.splice(i, 1));
break;
}
}
// Now reorder the array so that the last index of a subarray
// matches with the first index of the other subarray
for (let i = 0; i < result.length; i) {
for (let j = i 1; j < result.length; j) {
if (result[i][1] === result[j][0]) {
// recollocate the subarray so that it matches the way we want
result.splice(i 1, 0, ...result.splice(j, 1));
break;
}
}
}
console.log(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/416709.html
標籤:
