JavaScript Arrays unshift


In JavaScript, the Unshift array method adds new items to the beginning of an array and returns the new length. This method changes the length of an array.

Here is some sample code from w3schools.com

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon","Pineapple");

Unshift Objects

<!DOCTYPE html>
<html>
<body>
<script>
// ADD to an array of obects with the unshift() method.
// Output is sent to the browser console.
//
// This code demonstrates an array of objects that
// needs to be increased in size by two objects.
var fruits = [
  { name: "apple", value: 7 },
  { name: "banana", value: 3 },
  { name: "cherry", value: 9 }
];
// provided by user
var itemName = 'durian';
var itemValue = 1;

fruits.forEach(function(item, index){
    console.log(index + ' => ' + item.name + " " + item.value);
})

fruits.unshift({name: itemName, value: itemValue});
fruits.unshift({name: 'elderberry', value: 5});

console.log("After unshifting the durian and then the elderberry, the items are:");
fruits.forEach(function(item, index){
    console.log(index + ' => ' + item.name + " " + item.value);
})
</script>
</body>
</html>

Here is a screenshot of the console output in Google Chrome browser.

jsunshiftobjects

Leave a comment

Your email address will not be published. Required fields are marked *