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?
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.
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.
You can use either the spread operator [... array1, ... array2] , or a functional way []. concat(array1, array2) to merge 2 or more arrays.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With