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:
const numbers = [1, 2, 3, 4, 5]; const value = 3;
Now, let's use
filter() to remove the item from the array:
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:
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.
Using the combination of
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!