0

I have a reference to an array a1. I have an array of extra values a2. I want to concatenate all the values of a2 onto a1, mutating the original array.

Using concat() does not work, because it is non-mutating. For example:

var a0 = [1,2,3];
var a1 = a0;
var a2 = [4,5,6];
a1 = a1.concat(a2);
console.log(a1); // [1,2,3,4,5,6] YAY
console.log(a0); // [1,2,3]       BOO

Is there a better way to do this other than something like:

for (var i=0; i<a2.length; ++i) a1.push(a2[i]);
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • Thanks +Barmar. I was sure there had to be a duplicate, and I did search for a while, but somehow failed to find it. – Phrogz Dec 22 '17 at 22:45

1 Answers1

0

The mutating push() method accepts more than one argument. By using the apply() method you can pass all the values from a2 as parameters to push():

// Mutate a1 to have all the values of a2 added
a1.push.apply(a1, a2);

In action:

var a0 = [1,2,3];
var a1 = a0;
var a2 = [4,5,6];
a1.push.apply(a1, a2);
console.log(a1); // [1,2,3,4,5,6] YAY
console.log(a0); // [1,2,3,4,5,6] YAY!!
Phrogz
  • 296,393
  • 112
  • 651
  • 745