Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

I have a need to add or prepend elements toward the start of an array.

For instance, if my array looks like beneath:

[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 preparing 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?
by

2 Answers

aashaykumar

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

console.log(arr)
RoliMishra
Another way to do that through concat

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


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

Login / Signup to Answer the Question.