Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat 2 arrays, based on index

Tags:

javascript

I would like to merge 2 arrays:

arr1 = [["apple"], ["banana", "cherry"]]
arr2 = ["id1", "id2"]

I would like to get the output like:

result = [["apple id1"], ["banana id2", "cherry id2"]]

or

result = [["apple from id1"], ["banana from id2", "cherry from id2"]]

I have tried concat, but this is not keeping me the ID for each element. I am new in development overall, and I didn't find so far any results that would give me the proper output. Any hint how can I do this?

like image 830
vicky23 Avatar asked Apr 02 '19 09:04

vicky23


People also ask

How do I combine two indexes in an array?

In order to combine the two arrays by indices, we have to loop through them and merge as we go. Such that the first index of the first and second array together form the first index of the resultant array.

Can we concat two arrays?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

How do you merge two arrays using the spread Operator?

You can use either the spread operator [... array1, ... array2] , or a functional way []. concat(array1, array2) to merge 2 or more arrays.


2 Answers

Array#map is what you need.

arr1 = [["apple"], ["banana", "cherry"]]
arr2 = ["id1", "id2"]

var result = arr2.map((id, idx) => {
  return arr1[idx].map(item => item + " from " + id);
})

console.log(result);
like image 55
31piy Avatar answered Sep 22 '22 01:09

31piy


You could map the new items.

var arr1 = [["apple"], ["banana", "cherry"]],
    arr2 = ["id1", "id2"],
    result = arr1.map((a, i) => a.map(v => [v, arr2[i]].join(' ')));

console.log(result);
like image 20
Nina Scholz Avatar answered Sep 23 '22 01:09

Nina Scholz