[javascript] How can I add new array elements at the beginning of an array in Javascript?

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

This question is related to javascript arrays

The answer is


array operations image

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


If you want to push elements that are in a array at the beginning of you array use <func>.apply(<this>, <Array of args>) :

_x000D_
_x000D_
const arr = [1, 2];
arr.unshift.apply(arr, [3, 4]);
console.log(arr); // [3, 4, 1, 2]
_x000D_
_x000D_
_x000D_


Another way to do that through concat

_x000D_
_x000D_
var arr = [1, 2, 3, 4, 5, 6, 7];_x000D_
console.log([0].concat(arr));
_x000D_
_x000D_
_x000D_

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)
}

Here is the test result

enter image description here


you can first reverse array and then add elem to array then reverse back it.

const arr = [2,3,4,5,6];
const arr2 = 1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);

console.log(arr.reverse()); // [1,2,3,4,5,6]

good lock

ali alizadeh.


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.

Benchmark test: http://jsben.ch/kLIYf


you can reverse your array and push the data , at the end again reverse it:

var arr=[2,3,4,5,6];
var arr2=1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);

Without Mutate

Actually, all unshift/push and shift/pop mutate the origin array.

The unshift/push add an item to the existed array from begin/end and shift/pop remove an item from the beginning/end of an array.

But there are few ways to add items to an array without a mutation. the result is a new array, to add to the end of array use below code:

const originArray = ['one', 'two', 'three'];
const newItem = 4;

const newArray = originArray.concat(newItem); // ES5
const newArray2 = [...originArray, newItem]; // ES6+

To add to begin of original array use below code:

const originArray = ['one', 'two', 'three'];
const newItem = 0;

const newArray = (originArray.slice().reverse().concat(newItem)).reverse(); // ES5
const newArray2 = [newItem, ...originArray]; // ES6+

With the above way, you add to the beginning/end of an array without a mutation.


With ES6 , use the spread operator ... :

DEMO

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

console.log(arr)
_x000D_
_x000D_
_x000D_


Using splice we insert an element to an array at the begnning:

arrName.splice( 0, 0, 'newName1' );

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

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

_x000D_
_x000D_
var arr = [23, 45, 12, 67];_x000D_
arr.splice(0, 0, 34)_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_


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 ) 

Cheatsheet to prepend new element(s) into the array

1. Array#unshift

_x000D_
_x000D_
const list = [23, 45, 12, 67];

list.unshift(34);

console.log(list); // [34, 23, 45, 12, 67];
_x000D_
_x000D_
_x000D_

2. Array#splice

_x000D_
_x000D_
const list = [23, 45, 12, 67];

list.splice(0, 0, 34);

console.log(list); // [34, 23, 45, 12, 67];
_x000D_
_x000D_
_x000D_

3. ES6 spread...

_x000D_
_x000D_
const list = [23, 45, 12, 67];
const newList = [34, ...list];

console.log(newList); // [34, 23, 45, 12, 67];
_x000D_
_x000D_
_x000D_

4. Array#concat

_x000D_
_x000D_
const list = [23, 45, 12, 67];
const newList = [32].concat(list);

console.log(newList); // [34, 23, 45, 12, 67];
_x000D_
_x000D_
_x000D_

Note: In each of these examples, you can prepend multiple items by providing more items to insert.


Using ES6 destructuring: (avoiding mutation off the original array)

const newArr = [item, ...oldArr]