Categories
arrays javascript

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

2085

I have a need to add or prepend elements at the beginning 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 (var i = 0; i < theArray.length; i++) {
    newArray.push(theArray[i]);
}

theArray = newArray;
delete newArray;

Is there a 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.

3

  • 21

    FYI: If you need to continuously insert an element at the beginning of an array, it is faster to use push statements followed by a call to reverse, instead of calling unshift all the time.

    Feb 15, 2018 at 8:56


  • 2

    @JennyO’Reilly you should post this as an answer. Matched my use-case perfectly. thanks

    – rob

    Jun 7, 2018 at 12:19

  • 2

    Performance tests: jsperf.com/adding-element-to-the-array-start But the results are different for each browser.

    – Avernikoz

    Apr 23, 2019 at 18:34

3522

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


As pointed out in the comments, if you want to avoid mutating your original array, you can use concat, which concatenates two or more arrays together. You can use this to functionally push a single element onto the front or back of an existing array; to do so, you need to turn the new element into a single element array:

const array = [3, 2, 1]

const newFirstElement = 4

const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]

console.log(newArray);

concat can also append items. The arguments to concat can be of any type; they are implicitly wrapped in a single-element array, if they are not already an array:

const array = [3, 2, 1]

const newLastElement = 0

// Both of these lines are equivalent:
const newArray1 = array.concat(newLastElement) // [ 3, 2, 1, 0 ]
const newArray2 = array.concat([newLastElement]) // [ 3, 2, 1, 0 ]

console.log(newArray1);
console.log(newArray2);

3

  • 62

    Using concat might be preferable as it returns the new array. Very useful for chaining. [thingToInsertToFront].concat(originalArray).reduce(fn).reverse().map(fn) etc… If you use unshift, you can’t do that chaining because all you get back is the length.

    – StJohn3D

    Sep 23, 2016 at 18:27


  • 8

    shift/unshift, push/pop, splice. Very logical names for such methods.

    – linuxunil

    Apr 25, 2018 at 12:32

  • This one of the most easy to understand answers that I ever seen. Congrats for that.

    Apr 12 at 13:21

1617

array operations image

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

5

  • 179

    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, 2013 at 21:24

  • 95

    //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, 2013 at 21:05


  • 38

    @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

    – user229044

    Oct 22, 2013 at 13:06


  • 30

    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

    Sep 25, 2014 at 1:50

  • 6

    Mind that [23, 45, 12, 67].unshift(34) will not work. The Array must first be saved inside a variable, because unshift itself returns a value.

    – vsync

    Mar 15, 2017 at 15:12


326

With ES6, use the spread operator ...:

Demo

var arr = [23, 45, 12, 67];
arr = [34, ...arr]; // RESULT : [34,23, 45, 12, 67]

console.log(arr)

5

  • 32

    also creates a new array, useful for pure functions

    – devonj

    Aug 8, 2017 at 19:01

  • 1

    what is the performance implication here? Is it slower than using unshift()?

    – Peter T.

    Mar 2, 2018 at 9:49

  • 1

    Sure, it will be slower since it is an immutable array ( creating a new array). If you are working with a big array or the performance is your first requirement, please consider to use concat instead.

    Mar 2, 2018 at 15:42

  • performance is not important in 2018, new versions in browser and node get the same performance

    – stackdave

    Jul 16, 2018 at 6:11

  • 1

    @AbdennourTOUMI Just to clarify your comment. It is not creating an immutable array, it is just creating a new array without mutating the existing one.

    – Flimm

    Nov 11, 2021 at 11:38