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 Solid
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js