javascript pushing element at the beginning of an array

Javascript

Javascript Problem Overview


I have an array of objects and I'd like to push an element at the beginning of the of the array.

I have this:

var TheArray = TheObjects.Array;
TheArray.push(TheNewObject);

It's adding TheNewObject at the end. Do I need to create a new array, add TheNewObject to it and then loop through TheArray and add each element the to the array?

Javascript Solutions


Solution 1 - Javascript

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);

Solution 2 - Javascript

Use .unshift() to add to the beginning of an array.

TheArray.unshift(TheNewObject);

See MDN for doc on unshift() and here for doc on other array methods.

FYI, just like there's .push() and .pop() for the end of the array, there's .shift() and .unshift() for the beginning of the array.

Solution 3 - Javascript

For an uglier version of unshift use splice:

TheArray.splice(0, 0, TheNewObject);

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
QuestionfrenchieView Question on Stackoverflow
Solution 1 - JavascriptlonesomedayView Answer on Stackoverflow
Solution 2 - Javascriptjfriend00View Answer on Stackoverflow
Solution 3 - JavascriptWayneView Answer on Stackoverflow