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 OverflowMeticulous
meticulous.ai › blog › javascript-unshift-complete-guide
JavaScript Unshift | In-Depth Guide & Tutorial
The original array arr was mutated ... the .unshift call. Mutation is something to be careful about because it is a common cause of unexpected issues which can be tricky to debug. To drive this point home, the paradigm of functional programming has an explicit goal of avoiding mutation and having pure functions (functions without mutation or ...
Doesitmutate
doesitmutate.xyz
Does it mutate?
const array1 = [1, 2, 3]; console.log(array1.unshift(4, 5)); // Expected output: 5 console.log(array1); // Expected output: Array [4, 5, 1, 2, 3]
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › unshift
Array.prototype.unshift() - JavaScript | MDN
The unshift() method reads the length property of this. It shifts all indices in the range 0 to length - 1 right by the number of arguments (incrementing their values by this number). Then, it sets each index starting at 0 with the arguments passed to unshift().
Medium
vtechguys.medium.com › javascript-array-methods-mutating-vs-non-mutating-8606d9b78c77
Javascript: Array Methods | Mutating vs Non-Mutating | by Aniket Jha | Medium
May 24, 2020 - array.push() adds an item to the end and array.unshift() adds an item to the front of the array. There are two ways to do so array.concat() and …array spread operator. // Note use `const` to indicate that this will not be mutated const array1 = [1, 2, 3, 4, 5]; const array2 = array.concat(6); // [1, 2, 3, 4, 5, 6];const array3 = [...array1, 6]; // [1, 2, 3, 4, 5, 6]; const array4 = [10, ...array1]; // [10, 1, 2, 3, 4, 5];
W3Schools
w3schools.com › jsref › jsref_unshift.asp
JavaScript Array unshift() Method
cssText getPropertyPriority() getPropertyValue() item() length parentRule removeProperty() setProperty() JS Conversion ... const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon","Pineapple"); Try it Yourself »
Top answer 1 of 5
3
You are looking for the ShiftRight method which is unavailable in the prototype. Here is a pollyfill:
Array.prototype.shiftRight = function(...params) {
params.forEach(item => {
for (var i = this.length - 1; i >= 0; i--) {
if (i === 0)
this[0] = item
else
this[i] = this[i - 1];
}
})
}
x = [1, 2, 3];
x.shiftRight(4, 5);
console.log(x); // [5, 4, 1]
2 of 5
1
You could do something like this-
class arrWrapper(myArray: Array) {
this.arr = myArray;
this.len = myArray.length;
this.pos = 0;
unshift(newObj) {
//Add checks if lengeh > pos, do something - either return or pos = 0
this.arr[this.pos++] = newObj;
}
}
After comments I realize what you tried to do. This will "shift" the items up, without removing them:
class arrWrapper(myArray: Array) {
this.arr = myArray;
unshift(newObj) {
for (i=1; i<this.arr.length-1; i++) {
this.arr[i] = this.arr[i-1];
}
this.arr[0] = newObj;
}
}
this will run on the array, shift the cells up, and always insert the newObj into the first position
Another edit: oh sry, I didn't test it, you should go backwards to avoid the same item shift
Example with test:
function unshift(arr, newObj) {
for (i=arr.length-1; i>0; i--) {
arr[i] = arr[i-1];
}
arr[0] = newObj;
}
var testArr= [1,2,3,4];
unshift(testArr, "new1");
console.log(testArr);
unshift(testArr, "new2");
console.log(testArr);
unshift(testArr, "new3");
console.log(testArr);
unshift(testArr, "new4");
console.log(testArr);
Educative
educative.io › home › courses › simplifying javascript: a handy guide for software engineers › tip 8: avoid push mutations with the spread operator
Avoid Push Mutations Using the JavaScript Spread Operator
Node.js · // Add to beginning. const titles = ['Moby Dick', 'White Teeth']; titles.unshift('The Conscious Mind'); console.log("Titles after using unshift: " + titles) const moreTitles = ['Moby Dick', 'White Teeth']; const evenMoreTitles = ['The Conscious Mind', ...moreTitles]; console.log("Adding titles using spread operator: " + evenMoreTitles); // Copy ·
Doesitmutate
doesitmutate.xyz › unshift
unshift
const array1 = [1, 2, 3]; console.log(array1.unshift(4, 5)); // Expected output: 5 console.log(array1); // Expected output: Array [4, 5, 1, 2, 3]
Cheesecake Labs
cheesecakelabs.com › home › blog › engineering › how to avoid array mutation
How to Avoid Array Mutation
July 1, 2022 - To show an example of mutating, we’ll use the following array: const heroesMutate = ['Spider-man', 'Thor', 'Hulk', 'Iron Man']; console.log(heroesMutate); // => ["Spider-man", "Thor", "Hulk", "Iron Man"] ... heroesMutate.push('Captain Marvel'); console.log(heroesMutate); // => ["Spider-man", "Thor", "Hulk", "Iron Man", "Captain Marvel"] heroesMutate.unshift('Deadpool'); console.log(heroesMutate); // => ["Deadpool", "Spider-man", "Thor", "Hulk", "Iron Man", "Captain Marvel"] heroesMutate.splice(2, 0, 'Black Panther'); console.log(heroesMutate); // => ["Deadpool", "Spider-man", "Black Panther", "Thor", "Hulk", "Iron Man", "Captain Marvel"]
Lorenstewart
lorenstewart.me › 2017 › 01 › 22 › javascript-array-methods-mutating-vs-non-mutating
Lorenstewart
May 21, 2018 - // since the array will be mutated, // use 'let' rather than 'const' let mutatingAdd = ['a', 'b', 'c', 'd', 'e']; mutatingAdd.push('f'); // ['a', 'b', 'c', 'd', 'e', 'f'] mutatingAdd.unshift('z'); // ['z', 'a', 'b', 'c', 'd', 'e' 'f'] ... There are two ways to add new items to an array without mutating the original array.
Artem Sapegin
blog.sapegin.me › all › avoid-mutation
Washing your code: avoid mutation by Artem Sapegin
Info The Object.assign() method was introduced in ECMAScript 2015. Before that, we didn’t even try to avoid mutation — it was too painful. Info Redux has a great page on immutable update patterns: it describes patterns for updating arrays and objects without mutation, and it’s useful even if we don’t use Redux.
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › array.prototype.unshift()
JavaScript Array unshift() Method
November 6, 2024 - Note that the unshift() method modifies the original array. If you want to prepend an element and get the new array without modifying the original array, you can use the following syntax: