簡體   English   中英

在 JavaScript 中合並數組數組

[英]Merge array of arrays in JavaScript

我正在嘗試使用 JavaScript 在一個數組中合並兩個數組,但我沒有使用concat方法獲得確切的輸出。 誰能幫我?

  var a1= [[0, 1],[1, 5],[2,5],[3,7]];
  var a2= [[1,9],[0,6],[3,8],[2,6]];
//output 
  var result=[[0,1,6],[1,5,9],[2,5,6],[3,7,8]];

例如,對於 a1 中的每個數組,在 a2 中找到相應的(索引為零匹配的元素)數組並合並元素

我已經重新綁定的代碼

 var v1 = [[0, 1],[1, 5],[2,5]]; var v2 = [[0,5],[1,6],[2,8]]; const res = v1.map((x, i) => [...new Set([...x, ...v2[i]])]); console.log(res);

如果我們“從字面上”翻譯您的要求,一種解決方案可能如下所示:

 const a1 = [[0, 1], [1, 5], [2, 5], [3, 7]], a2 = [[1, 9], [0, 6], [3, 8], [2, 6]]; const result = a1.map(a1x => { // find the corresponding array const x2 = a2.find(a2x => a2x[0] === a1x[0]); // combine the values in a new array if (x2) { a1x = a1x.concat(x2); } // return an array of unique values return [...new Set(a1x)]; }); console.log(JSON.stringify(result));

將其最小化為單行取決於 OP :)

您可以使用Map ,收集按第一個元素分組的所有值,並返回一個包含鍵和值的數組。

 var a1 = [[0, 1], [1, 5], [2, 5], [3, 7]], a2 = [[1, 9], [0, 6], [3, 8], [2, 6]], result = Array.from( [a1, a2].reduce( (m, a) => a.reduce((n, [k, v]) => n.set(k, [...(m.get(k) || []), v]), m), new Map ), ([k, v]) => [k, ...v] ); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM