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.

3

5 Answers 5

3

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

this.array1 = [...this.array1, ...this.array2];
Sign up to request clarification or add additional context in comments.

4 Comments

About spread operator, you can use it also inside push: array1.push(...array2);
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.
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.
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
1

Try like this:

Working Demo

  copyArray() {
    this.array2.forEach(item => {
      this.array1.push(item);
    });
    this.array2 = [];
  }

4 Comments

Can you explain what this: this.array2 = []; does?
I assumed you added this.array2.splice(); to clear array2. this.array2 = []; simply make this array empty
Thanks alot! I used to like your answers.
You are welcome. The other answer is obviously better :)
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);

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.