Thursday, 17 March 2016

jquery - push information to an array but at index 0




I want to push information to an array I have created. The thing is I want to push the info to be first in the array, or at index 0. How do I do this?



I want to avoid having to reverse the array to get the most recent first as this makes things much complicated later..



e.g, my array may look like:



{"entry1":"entry1-value"}, {"entry2":"entry2-value"}



and I want to push a new value to be first:



{"newEntry":"newEntry-value"},{"entry1":"entry1-value"},{"entry2":"entry2-value"}

Answer



Use unshift():



array1.unshift({'newEntry' : 'newEntry-value'});



JS Fiddle demo.



References:




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...