[javascript] 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]

This question is related to javascript

The answer is


var a=[];
a.push({
 name_a:"abc",
 b:[]
});

a.b.push({
  name_b:"xyz"
});

You can use Array.concat:

var result = a.concat(b);

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.


Pushing multiple objects at once often depends on how are you declaring your array.

This is how I did

//declaration
productList= [] as  any;

now push records

this.productList.push(obj.lenght, obj2.lenght, items);

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:

_x000D_
_x000D_
var arr = [1];_x000D_
var newItems = [2, 3];_x000D_
var newerItems = [4, 5];_x000D_
var newArr = [...arr, ...newItems, ...newerItems];_x000D_
console.log(newArr);
_x000D_
_x000D_
_x000D_

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.


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

_x000D_
_x000D_
var arr = [1];_x000D_
var newItems = [2, 3];_x000D_
arr.push(...newItems);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

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


If you want to add multiple items, you have to use the spread operator

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

The output will be

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

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

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