Why doesn't Array.push.apply work?

JavascriptArraysApply

Javascript Problem Overview


As described here, a quick way to append array b to array a in javascript is a.push.apply(a, b).

You'll note that the object a is used twice. Really we just want the push function, and b.push.apply(a, b) accomplishes exactly the same thing -- the first argument of apply supplies the this for the applied function.

I thought it might make more sense to directly use the methods of the Array object: Array.push.apply(a, b). But this doesn't work!

I'm curious why not, and if there's a better way to accomplish my goal. (Applying the push function without needing to invoke a specific array twice.)

Javascript Solutions


Solution 1 - Javascript

It's Array.prototype.push, not Array.push

Solution 2 - Javascript

You can also use [].push.apply(a, b) for shorter notation.

Solution 3 - Javascript

The current version of JS allows you to unpack an array into the arguments.

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

Solution 4 - Javascript

What is wrong with Array.prototype.concat?

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstarwedView Question on Stackoverflow
Solution 1 - JavascriptVenView Answer on Stackoverflow
Solution 2 - JavascripterdemView Answer on Stackoverflow
Solution 3 - JavascriptDavid GriffinView Answer on Stackoverflow
Solution 4 - JavascriptphenomnomnominalView Answer on Stackoverflow