Arrays: Removing an item from an array

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' ]

You use 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 splice():

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))

// ["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.

Lessons in this unit:

0: Introduction
1: Number of items in an array
2: Create a new array from an existing array
3: Adding an item to an existing array
4: Adding at the beginning of an array
5: Adding multiple items to the array
6: ▶︎ Removing an item from an array
7: Modifying an existing array without mutating it
8: Arrays of arrays
9: Filling an array
10: Array destructuring
11: Check if an array contains a specific value
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!