You can actually accomplish this using the .concat method if you call it on an array of elements you want to put at the front of the new array.
Working Example:
var a = [1, 2, 3];
var b = [0].concat(a);
console.log(a);
console.log(b);
Alternately, in ECMAScript 6 you can use the spread operator.
Working Example (requires modern browser):
var a = [1, 2, 3]
var b = [0, ...a];
console.log(a);
console.log(b);
Answer from Alexander O'Mara on Stack OverflowI was working on an small project and the reviewer suggest using an alternative to unshift since its a time-costly operation. I considered array.concat and spread operator but they seem to be slower than array.unshift?
simple snippet of what im doing, basically prepending an item to an array. This operation is taking place in a function that is going to be called very often.
const arr1 = [1,2,3,4,5,7,8,9]
const newArr1 = arr1.unshift("...")Videos
EDIT: This is just venting, not confusion on how the word is technically used by JS :D
OK, this is why I keep starting and stopping learning JS- reserved words with extremely unrelated English meanings. "Unshift" means a previous shift occurred. That's the only meaning for it in English. But JS decided to use it as a prepend array method. Argh!!
That is all...
push() is faster.
js>function foo() {a=[]; start = new Date; for (var i=0;i<100000;i++) a.unshift(1); return((new Date)-start)}
js>foo()
2190
js>function bar() {a=[]; start = new Date; for (var i=0;i<100000;i++) a.push(1); return((new Date)-start)}
js>bar()
10
function foo() {a=[]; start = new Date; for (var i=0;i<100000;i++) a.unshift(1); return((new Date)-start)}
console.log(foo())
function bar() {a=[]; start = new Date; for (var i=0;i<100000;i++) a.push(1); return((new Date)-start)}
console.log(bar());
Update
The above does not take into consideration the order of the arrays. If you want to compare them properly, you must reverse the pushed array. However, push then reverse is still faster by ~10ms for me on chrome with this snippet:
var a=[];
var start = new Date;
for (var i=0;i<100000;i++) {
a.unshift(1);
}
var end = (new Date)-start;
console.log(`Unshift time: ${end}`);
var a=[];
var start = new Date;
for (var i=0;i<100000;i++) {
a.push(1);
}
a.reverse();
var end = (new Date)-start;
console.log(`Push and reverse time: ${end}`);
The JavaScript language spec does not mandate the time complexity of these functions, as far as I know.
It is certainly possible to implement an array-like data structure (O(1) random access) with O(1) push and unshift operations. The C++ std::deque is an example. A Javascript implementation that used C++ deques to represent Javascript arrays internally would therefore have O(1) push and unshift operations.
But if you need to guarantee such time bounds, you will have to roll your own, like this:
http://code.stephenmorley.org/javascript/queues/
Because strings are immutable, and unshift tries to assign to an index (property) of the string, as in
"hello"[4] = '1'
Reference: http://www.ecma-international.org/ecma-262/6.0/#sec-string-exotic-objects:
A String object is an exotic object that encapsulates a String value and exposes virtual integer indexed data properties corresponding to the individual code unit elements of the String value. Exotic String objects always have a data property named "length" whose value is the number of code unit elements in the encapsulated String value. Both the code unit data properties and the "length" property are non-writable and non-configurable.
join doesn't assign anything and only reads properties, therefore it works with any object that has .length.
Try this:
String.prototype.unshift = function(ch) {
return ch + this;
}
var s = "BCD";
s = s.unshift("A");
console.log(s); // ABCD
There are many ways to do this, but not as many that preserve the original aArr reference (e.g. modify the actual aArr array without creating a new one). Here's one way:
aArr.splice(0, bArr.length); // remove front-most bArr.length items from aArr
aArr.unshift.apply(aArr, bArr); // insert bArr items in front of aArr
This removes the first bArr.length items form aArr and then adds the bArr items to the front of aArr, all the while preserving the original aArr reference (e.g. not replacing it with a new array).
It can also be done in one .splice(), but that requires building a temporary array to pass to .splice.apply() which didn't seem worth it since that makes an entirely new array just to save one line of code. In any case, that would look like this:
aArr.splice.apply(aArr, [0, bArr.length].concat(bArr));
If you really want max "efficiency" in terms of performance rather than in terms of lines of code, then you will probably need to do performance benchmarks using a tool like jsperf and test in multiple browsers. It may be that simply copying over the bArr items into aArr is the most "efficient" because that has the fewest array manipulations. To know for sure, you would have to measure actual performance at your typical array sizes across several browsers.
For pure performance, you should test this vs the options above:
for (var i = 0, len = bArr.length; i < len; i++) {
aArr[i] = bArr[i];
}
This has the advantage that it does not create any temporary arrays and does not have to shift the items in aArr around. It has the disadvantage of running the loop in plain javascript, not in native array manipulation code.
It appears that the last option of just copying elements over is 7x faster in Chrome, 10x faster in IE11 and even more of a difference in Firefox.
See the jsperf here: http://jsperf.com/array-shift-vs-copy

function prependArray(a, b) {
return a.splice.apply(a, [0, b.length].concat(b))
}
Thanks The Paramagnetic Croissant (*_*)
You could Array#pop
The
pop()method removes the last element from an array and returns that element. This method changes the length of the array.
and Array#unshift.
The
unshift()method adds one or more elements to the beginning of an array and returns the new length of the array.
Copyvar array = ['Dog', 'Cat', 'Animal', 'Pig'];
array.push(array.shift());
console.log(array); // ["Cat", "Animal", "Pig", "Dog"]
array = ['Dog', 'Cat', 'Animal', 'Pig'];
array.unshift(array.pop());
console.log(array); // ["Pig", "Dog", "Cat", "Animal"]
Run code snippetEdit code snippet Hide Results Copy to answer Expand
It looks like you're looking for a rotate function:
CopyArray.prototype.rotate = (function() {
// save references to array functions to make lookup faster
var push = Array.prototype.push,
splice = Array.prototype.splice;
return function(count) {
var len = this.length >>> 0, // convert to uint
count = count >> 0; // convert to int
// convert count to value in range [0, len)
count = ((count % len) + len) % len;
// use splice.call() instead of this.splice() to make function generic
push.apply(this, splice.call(this, 0, count));
return this;
};
})();
a = [1,2,3,4,5];
a.rotate(1);
console.log(a.join(',')); //2,3,4,5,1
a.rotate(-1);
console.log(a.join(',')); //1,2,3,4,5
a.rotate(-1);
console.log(a.join(',')); //5,1,2,3,4
Run code snippetEdit code snippet Hide Results Copy to answer Expand