1

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.

Pleasure
  • 279
  • 2
  • 6
  • 19

5 Answers5

3

The spread operator (...) makes this easy.

this.array1 = [...this.array1, ...this.array2];
igg
  • 2,172
  • 3
  • 10
  • 33
  • 3
    About spread operator, you can use it also inside *push*: `array1.push(...array2);` – Christian Vincenzo Traina Dec 16 '19 at 15:19
  • 1
    Another thing to keep in mind is that `push` and `concat` don't change the reference and a lot of Angular change detection relies on variable reference changes for performance reasons. So, the *value* result of `array1.push(...array2)` and my answer above is the same. But mine also changes the reference, making it more likely to be picked up by Angular change detection. – igg Dec 16 '19 at 15:26
  • I have actually tried this before but I was getteing red line under the array2. It was just an editor problem. However, this works thatnks, I think I need the change editor. – Pleasure Dec 16 '19 at 15:34
  • Just one observation: ...this.array1, ...this.array2 is different from ...this.array2, ...this.array1 when using the spread operator with objects, the order determines the result when they have a key with same name with different values –  Dec 16 '19 at 15:43
1

Try like this:

Working Demo

  copyArray() {
    this.array2.forEach(item => {
      this.array1.push(item);
    });
    this.array2 = [];
  }
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
0

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);
0

Proper Angular approach is to use combination, you can either use ForkJoin or Concat, more details on official site.

Sam
  • 387
  • 4
  • 17
0

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);
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85