There are multiple ways an element can be removed from an array. We're going to discuss how to destructively and non destructively remove elements. It is crucial to think of how the code should run.
Destructively
There are two ways that elements can be added to an array with a destructive method. The reason they are called Destructive is because when used in a function they will change the original array with the passed in information.
.shift()
removes the first element in an array
.pop()
removes the last element in an array
The two methods are similar in these ways:
- They do not take any arguments
- They remove a single element
- They return the element that is removed
Nondestructively
This method works similar as the spread operator(...) if we don't add any arguments it will return a copy of the original array with all elements intact. Then removes an element without mutating the original array.
.slice()
We are able to add one-two arguments:
- First, is the index where the slice should begin
- Second, is the index where the slice should end
const snacks = ['Chips', 'Pretzels', 'M&Ms', 'Fruit', 'Veggies'];
const healthy = snacks.slice(3, 4);
In the example above we are creating a new variable and assigning pieces of the original array without mutating the original array.
Some great resources are linked below.
Top comments (2)
So when you use the .slice method in the example code. 'Fruit' and 'Veggies" will be taken out of the array correct?
They will be made into a new array under 'healthy' all while leaving the original 'snacks' array together. Where in .splice() it would destructively take them out of the array, and they would no longer be in 'snacks', just 'healthy'.
Hope that made sense :) !