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
39  
unshift – user479870 Nov 10 '11 at 0:37
up vote 1080 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

enter image description here

var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]
share|improve this answer
25  
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
29  
//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
12  
@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
14  
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
3  
thats why c# is so good you dont need so many comments around your code, the code just explains itself (in most cases) – CMS Mar 25 at 19:41

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];
> [0].concat(arr);
  [0, 1, 2, 3, 4, 5, 6, 7];

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)
}
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 at 9:12

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

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

arr.splice(0, 0, 34);
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 at 11:31

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.