let breads = [wheat, ciabatta, sourdough, brioche] breads.shift() // returns wheat console.log(breads) // [ciabatta, sourdough, brioche]
Using the shift method removes the first element in an array. It returns the first element and completely modifies the original array.
let fruits = [apple, banana, kiwi, orange] fruits.pop() // returns orange console.log(fruits) // [apple, banana, kiwi]
Using the pop method removes the last element in an array. It returns the last element and completely modifies the original array.
let cars = [Toyota, Ford, Jeep, BMW] cars.splice(1, 1) // returns [Ford] console.log(cars) // [Toyota, Jeep, BMW]
The splice method can be used to remove or add elements in an array. The first argument is the index location at which elements are to be removed or added. The second argument is the number of elements to be removed from the array. In the example above, the arguments call for one element at index one to be removed. This method returns a new array with the removed element and modifies the original array.
Using this method, you can remove a range of elements from an array.
let heroes = [Superman, Batman, Spiderman, Ironman, Thor, Hulk, Flash] heroes.splice(2, 4) // returns [Spiderman, Ironman, Thor, Hulk] console.log(heroes) // [Superman, Batman, Flash]
let shoes = [Nike, Adidas, Reebok, Jordan, Vans] shoes.slice(1, 4) // returns [Adidas, Reebok, Jordan] console.log(shoes) // [Nike, Adidas, Reebok, Jordan, Vans]
The slice method can be used to remove elements from an array without modifying the original array. The first argument specifies the starting index location and the second argument specifies the ending index location(the end is not included). A new array object will be created using the elements within the range of those indexes.