DzinX DzinX - 4 months ago 6
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

extend
method.

What I want to achieve is the following:

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


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

Answer

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