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

Most efficient way to prepend a value to an array

Assuming I have an array that has a size of N (where N > 0), is there a more efficient way of prepending to the array that would not require O(N + 1) steps?

In code, essentially, what I currently am doing is

function prependArray(value, oldArray) {
var newArray = new Array(value);

for(var i = 0; i < oldArray.length; ++i) {
newArray.push(oldArray[i]);
}

return newArray;
}
by

1 Answer

vishaljlf39
If you would like to prepend array (a1 with an array a2) you could use the following:

var a1 = [1, 2];
var a2 = [3, 4];
Array.prototype.unshift.apply(a1, a2);
console.log(a1);
// => [3, 4, 1, 2]

Login / Signup to Answer the Question.