I have two arrays that are made up of 20 arrays of objects. Like this:
var array1 = [
[
{'x':0,'y':0},
{'x':0,'y':0}
],
[
{'x':1,'y':1},
{'x':1,'y':1}
],
...
[
{'x':19,'y':19},
{'x':19,'y':19}
]
];
var array2 = [
[
{'x':0,'y':0},
{'x':0,'y':0}
],
[
{'x':1,'y':1},
{'x':1,'y':1}
],
...
[
{'x':19,'y':19},
{'x':19,'y':19}
]
];
I want the end result to be:
[
[
{'x':0,'y':0},
{'x':0,'y':0},
{'x':0,'y':0},
{'x':0,'y':0}
],
...
];
So I'm attaching two items in each array, meaning each array should contain four objects now.
What I tried was:
var array3 = array1;
array3.forEach(function(item,i) {
item.concat(array2[i])
})
But nothing was appended
Is there a less painstaking approach to concat items iteratively?
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
Example 1: Using concat() and for Loop In the above program, the two array elements are merged together and the duplicate elements are removed. Here, The two arrays are merged using the concat() method. The for...of loop is used to loop through all the elements of arr .
This is a fairly typical "zip" operation, can can be accomplished using map
.
var array1 = [
[
{'x':0,'y':0},
{'x':0,'y':0}
],
[
{'x':1,'y':1},
{'x':1,'y':1}
],
[
{'x':19,'y':19},
{'x':19,'y':19}
]
];
var array2 = [
[
{'x':0,'y':0},
{'x':0,'y':0}
],
[
{'x':1,'y':1},
{'x':1,'y':1}
],
[
{'x':19,'y':19},
{'x':19,'y':19}
]
];
var result = array1.map( (item,i) => item.concat(array2[i]));
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