Combine the sub-elements of each array into a new final array - JavaScript

Viewed 59

I have a data structure like this:

const arr1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]];
const arr2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]];

I want the final array to look like this:

finalArr = [["name1", "123", "prop2",156, 154, "position report], ["name2", "43", "prop22",173, 124, "position report"],["name3", "22", "prop3", 136, 154, "position report"]]

Basically I want to merge the sub-array elements of arr1 to arr2 in a new final array. I have tried to use this code but it just only merge the 2 arrays but not the sub elements

let newArr = [];
arr1.forEach((item) => {
arr2.forEach((element) => {
  newArr.push({ ...item, element });
   });
});

console.log(newArr);

Any ideas using only the ES6 notations?

3 Answers

You can use array.map to transform source array, take i as an index to get a corresponding element and use the spread operator to concatenate both arrays:

const arr1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]];
const arr2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]];

let result = arr1.map((item, i) => [...item, ...arr2[i]]);
console.log(result);

You could transpose the data by getting new arrays.

This approach works for more than two arrays.

const
    array1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]],
    array2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]],
    result = [array1, array2]
        .reduce((r, a) => a.map((v, i) => [...(r[i] || []), ...v]), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can do something like this:

const arr1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]];
const arr2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]];

let finalArr = [];
if (arr1.length === arr2.length) {
  for(let i=0; i<arr1.length; i++){
     finalArr.push([...arr1[i], ...arr2[i]]);
  }
}
Related