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 any 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.
you have an array:
var arr = [23, 45, 12, 67];
To add an item to the beginning, you want to use
splice
:If you need to continuously insert an element at the beginning of an array, it is faster to use
push
statements followed by a call toreverse
, instead of callingunshift
all the time.Benchmark test: http://jsben.ch/kLIYf
Another way to do that through
concat
The difference between
concat
andunshift
is thatconcat
returns a new array. The performance between them could be found here.Here is the test result
Quick Cheatsheet:
The terms shift/unshift and push/pop can be a bit confusing, at least to folks who may not be familiar with programming in C.
If you are not familiar with the lingo, here is a quick translation of alternate terms, which may be easier to remember:
Without Mutate
Actually, all
unshift
/push
andshift
/pop
mutate the origin array.The
unshift
/push
add an item to the existed array from begin/end andshift
/pop
remove an item from the beginning/end of an array.But there is a way to add items to an array without a mutation. the result is a new array, to add to end of array use below code:
To add to begin of original array use below code:
With the above way, you add to the beginning/end of an array without a mutation.