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.
I want to achieve 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
).
Note: This is not a duplicate of How to append something to an 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.
First a few words about
apply()
in JavaScript to help understand why we use it:Push expects a list of items to add to the array. The
apply()
method, however, takes the expected arguments for the function call as an array. This allows us to easilypush
the elements of one array into another array with the builtinpush()
method.Imagine you have these arrays:
and simply do this:
The result will be:
The same thing can be done in ES6 using the spread operator ("
...
") like this:Shorter and better but not fully supported in all browsers at the moment.
Also if you want to move everything from array
b
toa
, emptyingb
in the process, you can do this:and the result will be as follows:
This solution works for me (using the spread operator of ECMAScript 6):