How to Remove an Item from a JavaScript Array
Table of Contents
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:
JAVASCRIPTconst numbers = [1, 2, 3, 4, 5];
const value = 3;
Now, let's use filter()
to remove the item from the array:
JAVASCRIPTconst 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:
JAVASCIPTconst 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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js