Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend an existing JavaScript array with another array, without creating a new 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.

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.

like image 581
DzinX Avatar asked Sep 03 '09 15:09

DzinX


People also ask

Can array in JavaScript be extended?

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.

Can I append an array to another array?

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!

Can you splice an array?

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.

How do you push an array into an 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.


1 Answers

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.

like image 122
DzinX Avatar answered Sep 27 '22 17:09

DzinX