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;
}
I’m not sure about more efficient in terms of big-O but certainly using the
unshiftmethod is more concise:[Edit]
This jsPerf benchmark shows that
unshiftis 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:[Edit 2]
For completeness, the following function can be used instead of OP’s example
prependArray(...)to take advantage of the Arrayunshift(...)method: