Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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
35  
unshift – user479870 Nov 10 '11 at 0:37
up vote 901 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
16  
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
24  
//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
9  
@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
10  
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

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

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

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

Simple Demo ilustrating usage of those methods.

<!DOCTYPE html>
<html>
<body>

<p>DEMO html/javascript</p>

<button onclick="AddFront()">AddFront</button>
<button onclick="AddBack()">AddBack</button>

<button onclick="RemoveFromFront()">RemoveFromFront</button>
<button onclick="RemoveFromBack()">RemoveFromBack</button>

<p id="showMyArray"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("showMyArray").innerHTML = fruits;

function AddFront() {
    fruits.push("Kiwi");
    document.getElementById("showMyArray").innerHTML = fruits;
}

function AddBack() {
    fruits.unshift("Kiwi");
    document.getElementById("showMyArray").innerHTML = fruits;
}

function RemoveFromFront() {
    fruits.shift();
    document.getElementById("showMyArray").innerHTML = fruits;
}

function RemoveFromBack() {
    fruits.pop();
    document.getElementById("showMyArray").innerHTML = fruits;
}

</script>

</body>
</html>

share|improve this answer

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.

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.