Wednesday, 1 February 2017

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

First a few words about apply() in JavaScript to help understand why we use it:



The apply() method calls a function with a given this value, and
arguments provided as an array.



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 easily push the elements of one array into another array with the builtin push() method.


Imagine you have these arrays:


var a = [1, 2, 3, 4];
var b = [5, 6, 7];

and simply do this:


Array.prototype.push.apply(a, b);

The result will be:


a = [1, 2, 3, 4, 5, 6, 7];

The same thing can be done in ES6 using the spread operator ("...") like this:


a.push(...b); //a = [1, 2, 3, 4, 5, 6, 7];

Shorter and better but not fully supported in all browsers at the moment.


Also if you want to move everything from array b to a, emptying b in the process, you can do this:


while(b.length) {
a.push(b.shift());
}

and the result will be as follows:


a = [1, 2, 3, 4, 5, 6, 7];
b = [];

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...