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
Example of prepending in-place:
var A = [7,8,9]
var B = [1,2,3]
A.unshift(...B)
console.log(A) // [1,2,3,7,8,9]
f you need to preserve the old array, slice the old one and unshift the new value(s) to the beginning of the slice.
var oldA=[4,5,6];
newA=oldA.slice(0);
newA.unshift(1,2,3)
oldA+'\n'+newA
/* returned value:
4,5,6
1,2,3,4,5,6
*/
There is special method:
a.unshift(value);
But if you want to prepend several elements to array it would be faster to use such a method:
var a = [1, 2, 3],
b = [4, 5];
function prependArray(a, b) {
var args = b;
args.unshift(0);
args.unshift(0);
Array.prototype.splice.apply(a, args);
}
prependArray(a, b);
console.log(a); // -> [4, 5, 1, 2, 3]