20

What is the best way to concat arrays in mutating way in JS? My problem:

var a = [1,2,3]
var b = a;
a = a.concat([4,5,6]) //<-- typical way of array concatenation in JS
console.log(a) //[1,2,3,4,5,6]
console.log(b) //[1,2,3] <-- I'd like it to be the same like the first array

I can use some loop of course, but I wonder if there is some faster and cleaner way to achieve it.

Karol Selak
  • 4,248
  • 6
  • 35
  • 65

4 Answers4

40

push mutates an array, but it expects sequence of arguments, so we use apply:

var a = [1,2,3]
var b = a
a.push.apply(a, [4,5,6])
console.log(a) //=> [1, 2, 3, 4, 5, 6]
console.log(b) //=> [1, 2, 3, 4, 5, 6]

In ES6 you could use spread operator ...:

a.push(...[4, 5, 6])
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
4

You can use push.apply here to update a without creating a new variable:

a.push.apply(a, [4,5,6]);

Or perhaps the more easier to understand:

Array.prototype.push.apply(a, [4,5,6]);

DEMO

In short apply calls a function push with the first argument set as your this (object context), and the second argument an array. It's equivalent to a.push(element1, ..., element10), for example.

Andy
  • 61,948
  • 13
  • 68
  • 95
1

You can use the fact that push can take a variable number of arguments, and will push all of them to the end of the array. You can then write:

a.push.apply(a, [1, 2, 3]);

As apply will transform an array of arguments into an argument list for the function.

jackarms
  • 1,343
  • 7
  • 14
0

You can keep "a" as a property so that it can be accessed by reference:

var myObj = {};
myObj.a = [1,2,3]
var b = myObj;
myObj.a = myObj.a.concat([4,5,6])

console.log(myObj.a);
console.log(b.a);
McHat
  • 830
  • 5
  • 15