24

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.

0

4 Answers 4

44

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])
Sign up to request clarification or add additional context in comments.

2 Comments

var a = [1,2,3]; a.push.call(a, 10, 20, 30); console.log(a); // => [1, 2, 3, 10, 20, 30]
Or simply: a.push(4, 5, 6);
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.

Comments

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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.