Reputation: 319
I want to push just the objects of array2 into array1.
array1 = [{name:'first'}, {name:'second'}];
array2 = [{name:'third'}, {name:'fourth'}, {name:'five'}];
// Desired result
array1 = [{name:'first'}, {name:'second'}, {name:'third'}, {name:'fourth'}, {name:'five'}];
copyArray() {
this.array1.push( this.array2 );
this.array2.splice();
}
When I run the copyArray function, the array2 itself was instead copied and not the objects. I got this:
Unwanted result
array1 = [{name:'first'}, {name:'second'}, [{name:'third'}, {name:'fourth'}, {name:'five'}]];
Can someone help me to fix this.
Upvotes: 1
Views: 312
Reputation: 22723
Proper way is to use the concat function:
array2 = array1.concat(array2);
It can be use to merge two or more arrays like
var result = array1.concat(array2, array3, ..., arrayN);
Upvotes: 0
Reputation: 2250
The spread operator (...
) makes this easy.
this.array1 = [...this.array1, ...this.array2];
Upvotes: 3
Reputation: 548
Proper Angular approach is to use combination, you can either use ForkJoin or Concat, more details on official site.
Upvotes: 0
Reputation: 10384
It's unclear what you attempted to do. If you want to concatenate two arrays, just use .concat
:
const arr1 = [1, 2, 3];
const arr2 = [4, 5];
const arr3 = arr1.concat(arr2);
console.log('arr1', arr1); // unchanged
console.log('arr2', arr2); // unchanged
console.log('arr3', arr3);
Upvotes: 0
Reputation: 22213
Try like this:
copyArray() {
this.array2.forEach(item => {
this.array1.push(item);
});
this.array2 = [];
}
Upvotes: 1