shivu
shivu

Reputation: 171

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

Upvotes: 1

Views: 108

Answers (2)

Andreas
Andreas

Reputation: 21881

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

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386520

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

Upvotes: 0

Related Questions