我想知道在 javascript (ES6) 中執行此操作的最佳方法。
所以我有一個像這樣的二維陣列:
const two_dimensional_array = [
[33000, 100],
[33500, 200],
]
我現在有另一個二維陣列,如下所示:
const another_array = [
[33500, 1300]
]
another_array我希望它從in 中找到第一個值two_dimensional_array,然后將第二個值添加到其中。所以最終的結果two_dimensional_array是:
const two_dimensional_array = [
[33000, 100],
[33500, 1500],
]
uj5u.com熱心網友回復:
- 創建一個
Map,another_array其中鍵是對的第一個數字,值是第二個數字。 - 使用
Array#forEach, 迭代two_dimensional_array并嘗試檢查是否有要添加的數字(否則為 0)。
const
two_dimensional_array = [ [33000, 100], [33500, 200] ],
another_array = [ [33500, 1300] ];
const map = new Map(another_array);
two_dimensional_array.forEach(arr => arr[1] = map.get(arr[0]) ?? 0);
console.log(two_dimensional_array);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/419119.html
標籤:
