Just like when adding items, we can remove items from an array in 2 ways.
We can alter the original array, or you can create a new array without the item you want to remove.
That’s a big difference and you decide which way to go depending on the problem you are trying to solve.
Also, you can remove items depending on their value, or their position in the array.
We’ll just talk about the second option now. We’ll see removing by value later on when we’ll talk about `filter()
Let’s start by removing the last item from the array.
You can use the
pop() method of the array to do that:
const fruits = ['banana', 'pear', 'apple'] fruits.pop() //apple fruits //[ 'banana', 'pear' ]
shift() to remove the first item of an array:
const fruits = ['banana', 'pear', 'apple'] fruits.shift() //banana fruits //[ 'pear', 'apple' ]
To remove elements at a specific positions in the middle of the array you can use
const fruits = ['banana', 'pear', 'apple'] //remove the item at index 2 fruits.splice(2, 1) fruits //[ 'banana', 'pear' ]
All those methods mutate the original array.
If you want to create a new array without one specific item, you can first clone the array, or you can use
slice() (similar to before, but without the letter
p — yes, confusing).
Suppose you have an array, and you want to remove an item in position
i. You can do it in this way:
const items = ['a', 'b', 'c', 'd', 'e', 'f'] const i = 3 const filteredItems = items.slice(0, i-1).concat(items.slice(i, items.length)) console.log(filteredItems) // ["a", "b", "d", "e", "f"]
slice() creates a new array with the indexes it receives. We create a new array, from start to the index we want to remove, and concatenate another array from the first position following the one we removed to the end of the array.