xxxxxxxxxx
//Add element to front of array
var numbers = ["2", "3", "4", "5"];
numbers.unshift("1");
//Result - numbers: ["1", "2", "3", "4", "5"]
xxxxxxxxxx
var colors = ["white","blue"];
colors.unshift("red"); //add red to beginning of colors
// colors = ["red","white","blue"]
xxxxxxxxxx
const array = [2, 3, 4, 5]; // Example array
const newElement = 1; // Element to add
array.unshift(newElement);
console.log(array); // Output: [1, 2, 3, 4, 5]
xxxxxxxxxx
let arr = [4, 5, 6]
arr.unshift(1, 2, 3)
console.log(arr);
// [1, 2, 3, 4, 5, 6]
xxxxxxxxxx
// example:
let yourArray = [2, 3, 4];
yourArray.unshift(1); // yourArray = [1, 2, 3, 4]
// syntax:
// <array-name>.unshift(<value-to-add>);
xxxxxxxxxx
In JavaScript, you use the unshift() method
to add one or more elements to the beginning
of an array and it returns the array's
length after the new elements have been added.
example:
var colors = ['white', 'blue'];
colors.unshift('red');
console.log(colors);
// colors = ['red', 'white', 'blue']
var numbers = [2, 3, 4, 5];
numbers.unshift(1);
console.log(numbers);
// numbers: [ 1, 2, 3, 4, 5 ]
xxxxxxxxxx
// Use unshift method if you don't mind mutating issue
// If you want to avoid mutating issue
const array = [3, 2, 1]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]
console.log(newArray);
xxxxxxxxxx
for(var i = 0; i<$scope.notes.length;i++){
if($scope.notes[i].is_important){
var imortant_note = $scope.notes.splice(i,1);
$scope.notes.unshift(imortant_note[0]);//push to front
}
}
xxxxxxxxxx
let newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"]