Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 975
samccone Avatar asked Jun 01 '11 02:06

samccone


People also ask

How do I add a value to the front of an array?

Answer: Use the unshift() Method You can use the unshift() method to easily add new elements or values at the beginning of an array in JavaScript. This method is a counterpart of the push() method, which adds the elements at the end of an array. However, both method returns the new length of the array.

What is prepend array?

Inserts an array element at the beginning of an array and shifts the positions of the existing elements to make room.


2 Answers

I'm not sure about more efficient in terms of big-O but certainly using the unshift method is more concise:

var a = [1, 2, 3, 4]; a.unshift(0); // => [0, 1, 2, 3, 4] console.log({a});

[Edit]

This jsPerf benchmark shows that unshift is decently faster in at least a couple of browsers, regardless of possibly different big-O performance if you are ok with modifying the array in-place. If you really can't mutate the original array then you would do something like the below snippet, which doesn't seem to be appreciably faster than your solution:

a.slice().unshift(0); // Use "slice" to avoid mutating "a". 

[Edit 2]

For completeness, the following function can be used instead of OP's example prependArray(...) to take advantage of the Array unshift(...) method:

function prepend(value, array) {   var newArray = array.slice();   newArray.unshift(value);   return newArray; }  var x = [1, 2, 3]; var y = prepend(0, x); // x => [1, 2, 3]; // y => [0, 1, 2, 3]; console.log({ x, y });
like image 71
maerics Avatar answered Oct 03 '22 19:10

maerics


With ES6, you can now use the spread operator to create a new array with your new elements inserted before the original elements.

// Prepend a single item.  const a = [1, 2, 3];  console.log([0, ...a]);

// Prepend an array.  const a = [2, 3];  const b = [0, 1];  console.log([...b, ...a]);

Update 2018-08-17: Performance

I intended this answer to present an alternative syntax that I think is more memorable and concise. It should be noted that according to some benchmarks (see this other answer), this syntax is significantly slower. This is probably not going to matter unless you are doing many of these operations in a loop.

like image 38
Frank Tan Avatar answered Oct 03 '22 20:10

Frank Tan