In our previous lession we have learnt about an array, in this lession we will learn about some operations we can perform on an array. The operations we can perform on array are append new element to an array, removing element from an array and create another array with specific element from an existing array.
An array also can act as a stack. If we want to add new element to an existing array then we can use .push method. Using .push method we can add a new element at the end of array. For example we will create half array and then we will push some remaining elements to that array using .push method.
var monthNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9]; monthNumber.push(10); monthNumber.push(11); monthNumber.push(12); console.log(monthNumber); // Above code will print [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
If we want to remove some existing elements from an array then we can use .pop method. Using .pop method we can remove an element from the end of an array. In below code sample we will remove all 3 elements which we have added using .push method in previous example. For example
var monthNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; var lastElement = monthNumber.pop(); var secondLastElement = monthNumber.pop(); var thirdLastElement = monthNumber.pop(); console.log(lastElement); // This will print 12 console.log(secondLastElement); // This will print 11 console.log(thirdLastElement); // This will print 10
.shift method is also used to remove the element from an array, just difference is that it will remove an element from the begining of an array, or the remove the element as they are inserted in the array. So we can say it will act as queue, which element is inserted first, will be shift first. For example
var weekName = ; weekName.push('Mon'); weekName.push('Tues'); weekName.push('Wed'); weekName.push('Thurs'); console.log(weekName.shift()); // This will print Mon console.log(weekName.shift()); // This will print Tues console.log(weekName.shift()); // This will print Wed
.unshift method is also used to insert the element into an array, just difference is that it will insert an element at the begining of an array, For example
var weekName = ['Tues','Wed','Thurs']; weekName.unshift('Mon'); console.log(weekName); // This will print ["Mon", "Tues", "Wed", "Thurs"]
var monthName = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var spliceArray = monthName.splice(3, 4); console.log(monthName); // Output is : ["Jan", "Feb", "Mar", "Aug", "Sep", "Oct", "Nov", "Dec"] console.log(spliceArray); // Output is : ["Apr", "May", "Jun", "Jul"]