701

I have an array of objects and I'd like to push an element at the beginning of the of the array.

I have this:

var TheArray = TheObjects.Array;
TheArray.push(TheNewObject);

It's adding TheNewObject at the end. Do I need to create a new array, add TheNewObject to it and then loop through TheArray and add each element the to the array?

Paolo
  • 20,112
  • 21
  • 72
  • 113
frenchie
  • 51,731
  • 109
  • 304
  • 510

3 Answers3

1264

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
170

Use .unshift() to add to the beginning of an array.

TheArray.unshift(TheNewObject);

See MDN for doc on unshift() and here for doc on other array methods.

FYI, just like there's .push() and .pop() for the end of the array, there's .shift() and .unshift() for the beginning of the array.

learning2learn
  • 405
  • 5
  • 11
jfriend00
  • 683,504
  • 96
  • 985
  • 979
69

For an uglier version of unshift use splice:

TheArray.splice(0, 0, TheNewObject);
Wayne
  • 59,728
  • 15
  • 131
  • 126
  • 5
    why would you do that? – Елин Й. Sep 20 '17 at 19:40
  • 71
    Well as a programmer it is always very important to have options, sometimes the easy solutions dont always work in certain situations, and splice is a good way to remove items from arrays, so knowing how to insert with it is useful – Cacoon Feb 05 '18 at 21:40
  • 7
    in terms of readability, splice is more self-explanitory to me. `unshift` sounds like I'm removing something from an array (even though I'm not). `splice` sounds more like I'm merging 2 things together – chris.nesbit1 Aug 21 '19 at 20:05
  • 10
    What about performance? – Pwnstar Jul 17 '20 at 08:48
  • 1
    @Cacoon: The only use I can think of for "splice" in this instance is if the program is deciding at runtime whether or not to insert the array at the beginning. For example, –  Dec 08 '22 at 20:41
  • 1
    let spliceIndex = insert ? 0 : -1; TheArray.splice(spliceIndex,0,TheNewObject) –  Dec 08 '22 at 20:42