简体   繁体   中英

Merge array of arrays in JavaScript

I'm trying to Merge two arrays in a array using JavaScript but I'm not getting the exact output using concat method. Can any one help me?

  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]];

for example for every array in a1 find the corresponding (the elements at index zero match) array in a2 and merge the elements

code which I have retied

 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);

If we translate your requirement "literally" one solution could look like this:

 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));

Minimizing this into a one-liner is up to OP :)

You could take a Map , collect all values grouped by the first element and return an array of arrays with key and values.

 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM