16

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 a here

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

Karol Selak
  • 3,659
  • 4
  • 28
  • 60

4 Answers4

31

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
  • 28,931
  • 5
  • 62
  • 77
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
  • 53,323
  • 11
  • 64
  • 89
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
  • 800
  • 4
  • 14