'Making an array from two another

I have two arrays of objects (10 objects in each arrray) ->

arr1 = [{name: '', age: ''}...]

and

arr2 = [{surname: '', position: ''}...]

which I hold in two separated states. My goal is to create the third array of the objects which contains also 10 elements

arr3=[{name: arr1.name, surname: arr2.surname}...]

How can I do this ?



Solution 1:[1]

As long as it is a 1 to 1 where each index matches, it is a simple Array map and using the spread to copy over the properties and values.

const arr1 = [{a: 1, b: 2}, {a: 3, b: 4}];
const arr2 = [{c: 11, d: 22}, {c: 33, d: 44}];

const arr3 = arr1.map((obj, ind) => ({...obj, ...arr2[ind]}), []);

console.log(arr3);

Solution 2:[2]

This is what you need,

let arr3 = []    
arr1.forEach((obj1, index) => {
 let obj3 = {...obj1, ...arr2[index]}
 arr3.push(obj3)
})

Solution 3:[3]

If the indexes are assumed to match between the two arrays (which also implies that the two arrays are the same length), you can use map() on one array and use its index parameter to reference the other array. (It doesn't really matter which.)

For example:

const arr3 = arr1.map((a, i) => ({
  name: a.name,
  surname: arr2[i].surname
}));

Note that this is based on the example shown, where only two properties (one from each array) are in the resulting objects. If you want all properties in the resulting objects, you don't need to specify all of them. You can just combine them all:

const arr3 = arr1.map((a, i) => ({
  ...a,
  ...arr2[i]
}));

Solution 4:[4]

Here is how you could combine both arrays using a for loop:

const arr3 = []
for (let i = 0; i < arr1.length; i++) {
  arr3[i] = {
    name: arr1[i].name,
    surname: arr2[i].surname
  }
}

Solution 5:[5]

I don't get exactly what do you want to do but I think this question has been answered a few times.

You wanna do arr1 + arr2 ? Like they follow each others in the array3 ?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 epascarello
Solution 2 Abrah_dago_313
Solution 3
Solution 4 Zach Jensz
Solution 5 Raphoudre