424

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]
Penny Liu
  • 11,885
  • 5
  • 66
  • 81
evfwcqcg
  • 14,775
  • 14
  • 52
  • 70

13 Answers13

790

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

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

console.log(a);
amit1310
  • 8,217
  • 2
  • 11
  • 12
  • 1
    This answer and the selected answer produce different, and perhaps unexpected, results. a.push(1) vs. a.push([1]) – oevna Dec 24 '16 at 01:12
  • 3
    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. – Tigerware Sep 17 '19 at 14:49
  • 2
    @BluE if you want to merge two arrays just use array.concat() – Florent Arlandis Feb 26 '20 at 16:45
  • 1
    @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. – Tigerware Feb 27 '20 at 07:55
  • 7
    @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) – vantrung -cuncon Sep 06 '20 at 21:12
617

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

John
  • 6,714
  • 2
  • 37
  • 57
canac
  • 13,824
  • 2
  • 14
  • 11
  • 49
    whaaaaaaat this is awesome, plus, if you do it in typescript it will compile to push.apply so you have backward compatibility – Chris Feb 15 '16 at 17:40
  • This has array size limitation. Try with big arrays. You will get exception. – SalientBrain Sep 07 '21 at 13:56
304

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

Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566
86

You can use Array.concat:

var result = a.concat(b);
VisioN
  • 138,460
  • 30
  • 271
  • 271
  • 24
    Array.prototype.concat returns new array. – suricactus Aug 21 '15 at 21:38
  • 12
    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 Aug 21 '15 at 22:18
  • 4
    @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. – VisioN Aug 21 '15 at 22:47
  • Are you guys sure `prototype.push.apply` works faster than `.concat`? I think `apply` might actually be slower, since it probably calls `push` again and again for each item in `arr2` – Yuval A. May 09 '16 at 12:08
  • 5
    @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. – coderforlife Sep 02 '16 at 14:58
  • Not considering the fact it does not A the Q, I want to add that the reason using `.concat` is 'slow', or inefficient, especially with large arrays, is because the VM will need to GC the old array, impacting performance considerably. – origo Aug 22 '17 at 13:13
  • @origo Are you sure about that? Optimisation mechanisms are not that stupid and may "understand" your intensions. For example, the best way to append values to array (slice) in Golang is doing `a = append(a, 1, 2, 3)`, although internally `append` will always return a new slice. Same may work in JS, as the new array will immediately replace the old one in memory. Anyway, this is all theory, we need JSPerf here to prove the word "considerably". And yes, it does A the Q, as it does exactly what is required, if used as `a = a.concat([1, 2, 3])`. – VisioN Aug 23 '17 at 18:45
  • 1
    ```a = a.concat(b)``` is still a shorter syntax than ```Array.prototype.push.apply(arr1, arr2)``` – Aizzat Suhardi Nov 07 '17 at 04:52
47

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]
Nikhil Yadav
  • 879
  • 1
  • 10
  • 4
25

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.

John
  • 6,714
  • 2
  • 37
  • 57
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.

12kb
  • 105
  • 3
  • 5
  • 4
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. [How do I write a good answer? ](https://stackoverflow.com/help/how-to-answer) – mrun Apr 04 '18 at 14:03
  • 1
    Sorry, i can't leave comments under answers (except my own) because of not enough reputation :). But seems this should be mentioned here to have complete overview. Could you please do it for me? Then i'll remove my answer. – 12kb Apr 05 '18 at 13:34
5

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)
MD SHAYON
  • 7,911
  • 47
  • 35
2

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', {} ]
Jose Velasco
  • 143
  • 2
  • 6
1

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);
R15
  • 10,727
  • 13
  • 68
  • 139
  • "Type assertion expressions can only be used in TypeScript files." is what VS Code said about the keyword `any` here – Ramon Dias Mar 06 '21 at 05:02
0

Option 1: Using concat(): It takes extra space as it returns a new array.

let array1=['a','b']
let array2=['c','d']
let array3=['e','f']
let res=array1.concat(array2,array3)

Option 2: Using spread operator: Doesn't takes extra space and operates on the same array.

let array1=['a','b']
let array2=['c','d']
let array3=['e','f']
array1.push(...array2,...array3)
sakigo
  • 55
  • 6
-2

Please use ES6 spread operator:

let a = [1,2,3];
let b = [4,5,6];
a = [...a,...b];
// [1,2,3,4,5,6]
  • No, this creates a new array so is not the same as `push` so is not an answer to the question. – James Dec 22 '21 at 11:26
-3
var a=[];
a.push({
 name_a:"abc",
 b:[]
});

a.b.push({
  name_b:"xyz"
});
Alex Kumbhani
  • 137
  • 2
  • 10
  • While this code block may answer the question, it would be best if you could provide a little explanation for why it does so. – nik7 May 08 '21 at 19:32