How can I add new array elements at the beginning of an array in JavaScript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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.

Answers

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push

    • 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

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/8073673/how-can-i-add-new-array-elements-at-the-beginning-of-an-array-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils