How to Remove an Item from a JavaScript Array

Updated onbyAlan Morel
How to Remove an Item from a JavaScript Array

With arrays being a fundamental part of the language, JavaScript has several methods that can be used to remove items from an array.

In this post, we're going to look at these methods, and explore how you can remove items from an array if you know the index or value of the item.

Removing an Item from an Array by Value

This is the most common scenario. You have the value of an item in the array, and you want to remove it.

The best method to use here is the filter() method, which takes a function that returns a boolean value.

Here's an example array and value we want to remove:

JAVASCRIPT
const numbers = [1, 2, 3, 4, 5]; const value = 3;

Now, let's use filter() to remove the item from the array:

JAVASCRIPT
const numbers = [1, 2, 3, 4, 5]; const value = 3; const filteredNumbers = numbers.filter(number => number !== value); // [1, 2, 4, 5]

In general, just define a function that test if your value matches the value inside the array, and return true if it does, or false if it doesn't. The function will take care of the rest.

Removing an Item from an Array by Index

In other cases, you don't know the value of the item, but you know the index you want to remove. In this scenario, you can utilize the splice() array method.

This method takes the index of the item you want to remove, and the number of items you want to remove.

Let's see an example of this:

JAVASCIPT
const numbers = [1, 2, 3, 4, 5]; const index = 2; numbers.splice(index, 1); console.log(numbers); // [1, 2, 4, 5]

As expected, the function removed the item at the specified index.

Conclusion

Using the combination of filter() and splice(), you can remove items from an array if you know the value or index of the item you want removed.

This is a powerful combination that gives you full control over how you want to remove items from an array.

Hopefully, this has helped you. Happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.