push multiple elements to array


push multiple elements to array

I’m trying to push multiple elements as one array, but getting error
> a = []
> a.push.apply(null, [1,2])
TypeError: Array.prototype.push called on null or undefined

I’m trying to do similar stuff that I’d do in ruby, I was thinking that apply is something like *.
>> a = []
=> []
>> a.push(*[1,2])
=> [1, 2]


Solution 1:

When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.

In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))

Solution 2:

You can push multiple elements into an array in the following way

var a = [];
a.push(1, 2, 3);


Solution 3:

Now in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:

var arr = [1];
var newItems = [2, 3];

See Kangax’s ES6 compatibility table to see what browsers are compatible

Solution 4:

You can use Array.concat:

var result = a.concat(b);

Solution 5:

If you want an alternative to Array.concat in ECMAScript 2015 (a.k.a. ES6, ES2015) that, like it, does not modify the array but returns a new array you can use the spread operator like so:

var arr = [1];
var newItems = [2, 3];
var newerItems = [4, 5];
var newArr = [...arr, ...newItems, ...newerItems];

Note this is different than the push method as the push method mutates/modifies the array.

If you want to see if certain ES2015 features work in your browser check Kangax’s compatibility table.

You can also use Babel or a similar transpiler if you do not want to wait for browser support and want to use ES2015 in production.

Solution 6:

There are many answers recommend to use: Array.prototype.push(a, b). It’s nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.

See What is the most efficient way to concatenate N arrays? for more details.