I have a need to add or prepend elements at the beginning of an array.
For example, if my array looks like below:
[23, 45, 12, 67]
And the response from my AJAX call is 34, I want the updated array to be like the following:
[34, 23, 45, 12, 67]
Currently I am planning to do it like this:
var newArray = [];
newArray.push(response);
for (var i = 0; i < theArray.length; i++) {
newArray.push(theArray[i]);
}
theArray = newArray;
delete newArray;
Is there a better way to do this? Does JavaScript have any built-in functionality that does this?
The complexity of my method is O(n) and it would be really interesting to see better implementations.
Use
unshift. It’s likepush, except it adds elements to the beginning of the array instead of the end.unshift/push– add an element to the beginning/end of an arrayshift/pop– remove and return the first/last element of an arrayA simple diagram…
and chart:
pushpopunshiftshiftCheck out the MDN Array documentation. Virtually every language that has the ability to push/pop elements from an array will also have the ability to unshift/shift (sometimes called
push_front/pop_front) elements, you should never have to implement these yourself.As pointed out in the comments, if you want to avoid mutating your original array, you can use
concat, which concatenates two or more arrays together. You can use this to functionally push a single element onto the front or back of an existing array; to do so, you need to turn the new element into a single element array:concatcan also append items. The arguments toconcatcan be of any type; they are implicitly wrapped in a single-element array, if they are not already an array: