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 Array unshift() The unshift() method adds new elements to the beginning of an array. The unshift() method overwrites the original 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.
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.
Use unshift
, which modifies the existing array by adding the arguments to the beginning:
TheArray.unshift(TheNewObject);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With