Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a need to add elements (I retrieve on timely basis using AJAX) at the top 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 (int 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.

share|improve this question
47  
unshift – user479870 Nov 10 '11 at 0:37
up vote 1287 down vote accepted

Use unshift. It's like push, 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 array
  • shift/pop - remove and return the first/last element of and array

A simple diagram...

   unshift -> array <- push
   shift   <- array -> pop

and chart:

          add  remove  start  end
   push    X                   X
    pop           X            X
unshift    X             X
  shift           X      X

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

share|improve this answer
4  
Using concat might be preferable as it returns the new array. Very useful for chaining. [thingToInsertToFront].concat(originalArray).reduce(fn).reve‌​rse().map(fn) etc... If you use unshift, you can't do that chaining because all you get back is the length. – St. John Peaster Sep 23 '16 at 18:27

array operations image

var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]

share|improve this answer
45  
The reason why people need a visual guideline for 4 everyday used functions is because of the encrypted function names... Why is unshift not called Insert? Shift should be Remove. etc... – Pascal Jun 29 '13 at 21:24
39  
//Why is unshift not called Insert?// It comes from the conventions of the C programming language where array elements were treated like a stack. (see perlmonks.org/?node_id=613129 for a complete explanation) – dreftymac Jul 26 '13 at 21:05
14  
@Pascal No, insert and remove would be particularly bad names for this; they imply random access, instead of adding/removing from the front of the array – meagar Oct 22 '13 at 13:06
15  
I would have thought that unshift should remove the first key, and shift would insert at the first key, but that's just my general thought – Shannon Hochkins Sep 25 '14 at 1:50
9  
I like the DNA reference – MrHunter May 20 '16 at 0:54

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:

* array_unshift()  -  (aka Prepend ;; InsertBefore ;; InsertAtBegin )     
* array_shift()    -  (aka UnPrepend ;; RemoveBefore  ;; RemoveFromBegin )

* array_push()     -  (aka Append ;; InsertAfter   ;; InsertAtEnd )     
* array_pop()      -  (aka UnAppend ;; RemoveAfter   ;; RemoveFromEnd ) 
share|improve this answer

Another way to do that through concat

var arr = [1, 2, 3, 4, 5, 6, 7];
console.log([0].concat(arr));

The difference between concat and unshift is that concat returns a new array. The performance between them could be found here.

function fn_unshift() {
  arr.unshift(0);
  return arr;
}

function fn_concat_init() {
  return [0].concat(arr)
}

Here is the test result

enter image description here

share|improve this answer
    
It would be good for your answer to append the performance comparison of both apart from adding the reference. – Ivan De Paz Centeno Jun 15 '16 at 9:12
    
I just got jsPerf is temporarily unavailable while we’re working on releasing v2. Please try again later from the link. Another good reason to include the results instead of linking to them. – Tigger Aug 21 '16 at 1:00
    
jsPref result: unshift: 25,510 ±3.18% 99% slower concat: 2,436,894 ±3.39% fastest – Illuminator Nov 3 '16 at 10:28

With ES6 , use the spread operator ... :

var arr=[23, 45, 12, 67] ;
arr=[34,...arr]; // RESULT : [34,23, 45, 12, 67] 
share|improve this answer

you have an array: var arr = [23, 45, 12, 67];

To add an item to the beginning, you want to use splice:

var arr = [23, 45, 12, 67];
arr.splice(0, 0, 34)
console.log(arr);

share|improve this answer
    
arr.splice(0, arr.length, 34); – Lior Elrom Oct 15 '15 at 20:08
1  
@LiorElrom what does your snippet do? – Janus Troelsen Jun 22 '16 at 11:31
    
Yes! splice is faster than unshift. jsperf.com/array-unshift-vs-splice – poushy Jan 14 at 17:19

protected by Community Jul 9 '15 at 10:02

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.