Removing Elements From An Array
codethepotato
Posted on June 25, 2023
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.
Posted on June 25, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.