1

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

5
  • 3
    What is the expected output? Also, what didn't work with concat()? Commented Mar 16, 2020 at 12:42
  • 1
    can you explain your logic behind your output/result array? Commented Mar 16, 2020 at 12:42
  • 2
    @NickParsons Seems to be: for every array in a1 find the corresponding (the elements at index zero match) array in a2 and merge the elements Commented Mar 16, 2020 at 12:44
  • @Andreas ah, I see, thanks :). That seems correct Commented Mar 16, 2020 at 12:45
  • @Andreas you are correct Commented Mar 16, 2020 at 12:48

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.