538

I'm trying to push multiple elements as one array, but getting an 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]
1
  • Your example was almost correct, it only required to put a in place of null, like this: a.push.apply(a, [1,2]) Commented Nov 20, 2023 at 11:24

9 Answers 9

889

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

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

console.log(a);

Sign up to request clarification or add additional context in comments.

5 Comments

This answer and the selected answer produce different, and perhaps unexpected, results. a.push(1) vs. a.push([1])
Can anyone explain, why this has so many more votes than the accepted answer? It might be easier, but is less flexible. If you want to merge 2 arrays, this wont work.
@BluE if you want to merge two arrays just use array.concat()
@FlorentArlandis array.concat does not work to add the 2nd array to the first. It will create a new one. I know it is similar. The spread operator is what I was looking for. Just look at the other answers and comments there for details.
@BluE ES6 now allow you to do something like this array1.push(...array2) that works exactly like array1.push(array2[0], array2[1], array2[2]) except a limitation of number of elements in array2 (about 100,000)
739

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];
arr.push(...newItems);
console.log(arr);

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

4 Comments

whaaaaaaat this is awesome, plus, if you do it in typescript it will compile to push.apply so you have backward compatibility
This has array size limitation. Try with big arrays. You will get exception.
I wanted to know more about the size limitation so I tried it. a = []; b = []; for (let i = 0; i < 1000000; i++) { b.push(i); } a.push(...(b.slice(0, 130000))); This indeed causes an error for me. "Uncaught RangeError: Maximum call stack size exceeded" The limit may depend on the size of elements in the array, not just the number of elements. That's just a guess. It may depend on the environment. Also just a guess. I haven't tried looking for documentation.
What about the performance of this operation vs using each element separately?
319

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]))

3 Comments

Is there a limit to how many elements can be pushed with this method? I know JavaScript has an argument limit, is this the case when using the "apply" function?
I believe it's 65,535 in older browsers, practically unlimited (4B) in modern ones.
The limit is pretty low in node (v20.4.0) with default settings. I didn't find the exact value but it's somewhere between 1<<16 and 1<<17.
100

As one alternative, you can use Array.concat:

var result = a.concat(b);

This would create and return a new array instead of pushing items to the same array. It can be useful if you don't want to modify the source array but rather make a shallow copy of it.

10 Comments

Array.prototype.concat returns new array.
He wants to push to existing array so Array.prototype.push.apply(arr1, arr2) is the correct answer, because using arr1.concat(arr2) you are creating a new array.
@suricactus arr1 = arr1.concat(arr2) is not a big deal and looks much cleaner. Pushing to old array or replacing old array with the new one depends on your needs. If you deal with 10m+ elements pushing to old array will work faster, if you manage small chunks you hardly find any difference in speed. Both options a completely legit.
@YuvalA. prototype.push.apply only calls push once. And the distinction above isn't necessary about speed but an in-place operation vs creating a new array. What if I had a method that took an array and was supposed to modify it in-place? The concat method cannot possibly work, even with VisionN's code as it won't modify the variable for the caller of the function.
a = a.concat(b) is still a shorter syntax than Array.prototype.push.apply(arr1, arr2)
|
29

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];
console.log(newArr);

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.

Comments

3

Easier way is

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

Another way is

a = [...a, 4,5,6]

if you want to create another array

const b = a.concat(7,8,9)

1 Comment

Easier than what? These are the exact approaches given in this 10 year old answer and this 7 year old answer
3

I had the same doubt and in my case, an easier solution worked for me:

let array = []
array.push(1, 2, 4, "string", new Object())
console.log(array)
// logs [ 1, 2, 4, 'string', {} ]

3 Comments

Easier than what? This is the exact approach given in this 10 year old answer
Does copying the same comment over and over give you points? I try to contribute, others...
@JoseVelasco Posting the same approach wastes time of millions of readers
1

Imagine you have an array of first ten numbers but missing a number, say 6. You can insert it into the array at the index 5 with the following code

function insert(array, index, obj) {
  return [...array.slice(0,index), obj, ...array.slice(index)]
}

let arr = [1,2,3,4,5,7,8,9,0]
arr = insert(arr, 5, 6)
console.log(arr)

Comments

0

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.length, obj2.length, items);

1 Comment

"Type assertion expressions can only be used in TypeScript files." is what VS Code said about the keyword any here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.