Thursday, 15 June 2017

javascript pushing element at the beginning of an array




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?


Answer



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



TheArray.unshift(TheNewObject);


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...