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
- Getting Started with Svelte
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications