DzinX DzinX - 1 year ago 81
Javascript Question

How to extend an existing JavaScript array with another array, without creating a new array?

Note: This is not a duplicate of Appending to array -- the goal here is to add the whole contents of one array to the other, and to do it "in place", i.e. without copying all elements of the extended array.

There doesn't seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python's


What I want to achieve is the following:

>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> a
[1, 2, 3, 4, 5]

I know there's a
method, but it creates a new array instead of simply extending the first one. I'd like an algorithm that works efficiently when
is significantly larger than
(i.e. one that does not copy

Answer Source

The .push method can take multiple arguments, so by using .apply to pass all the elements of the second array as arguments to .push, you can get the result you want:

>>> a.push.apply(a, b)

or perhaps, if you think it's clearer:

>>> Array.prototype.push.apply(a,b)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download