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.
We can extend the standard Array class and add new methods or redefine the existing ones. The of method on the new extended class creates a new extended array. The standard array methods like filter and map called on extended array return extended arrays.
To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array. The method changes the contents of the original array. Copied!
The splice() method returns the removed items in an array. The slice() method returns the selected element(s) in an array, as a new array object. The splice() method changes the original array and slice() method doesn't change the original array.
Adding Array into the Array using push() To add an array into an array in JavaScript, use the array. push() method. The push() function allows us to push an array into an array.
The .push
method can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push
:
>>> a.push(...b)
If your browser does not support ECMAScript 6, you can use .apply
instead:
>>> a.push.apply(a, b)
Or perhaps, if you think it's clearer:
>>> Array.prototype.push.apply(a,b)
Please note that all these solutions will fail with a stack overflow error if array b
is too long (trouble starts at about 100,000 elements, depending on the browser).
If you cannot guarantee that b
is short enough, you should use a standard loop-based technique described in the other answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With