Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript pushing element at the beginning of an array [duplicate]

Tags:

javascript

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?

like image 951
frenchie Avatar asked Nov 16 '11 22:11

frenchie


People also ask

How do you insert an item at the beginning of an array in JavaScript?

JavaScript Array unshift() The unshift() method adds new elements to the beginning of an array. The unshift() method overwrites the original array.

How do you push a value to the front of an array?

Answer: Use the unshift() Method You can use the unshift() method to easily add new elements or values at the beginning of an array in JavaScript. This method is a counterpart of the push() method, which adds the elements at the end of an array. However, both method returns the new length of the array.

Does push modify the original array?

push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements.


1 Answers

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

TheArray.unshift(TheNewObject); 
like image 139
lonesomeday Avatar answered Sep 20 '22 19:09

lonesomeday