The Question :
555 people think this question is useful
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;
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?
The Question Comments :
The Answer 1
1055 people think this answer is useful
unshift, which modifies the existing array by adding the arguments to the beginning:
The Answer 2
126 people think this answer is useful
.unshift() to add to the beginning of an array.
See MDN for doc on
unshift() and here for doc on other array methods.
FYI, just like there’s
.pop() for the end of the array, there’s
.unshift() for the beginning of the array.
The Answer 3
49 people think this answer is useful
For an uglier version of
TheArray.splice(0, 0, TheNewObject);