How to remove item from array by value?

 

You can remove an item from an array in JavaScript by value using various methods. One common approach is to use the filter() method, which creates a new array that includes all elements except the one you want to remove. Here's an example:

javascript
// Sample array var fruits = ["apple", "banana", "cherry", "date"]; // Value to remove var valueToRemove = "banana"; // Use the filter() method to remove the item by value var filteredFruits = fruits.filter(function (fruit) { return fruit !== valueToRemove; }); // The filteredFruits array now contains the original array without the item console.log(filteredFruits);

In this example:

  1. We have an array called fruits that contains various fruit names.

  2. We specify the valueToRemove variable, which contains the value we want to remove from the array (in this case, "banana").

  3. We use the filter() method on the fruits array to create a new array called filteredFruits. The filter() method iterates through each element in the original array and includes only those elements that do not match the valueToRemove using the provided callback function.

  4. After running this code, the filteredFruits array will contain all the elements from the original array except for "banana."

The result of console.log(filteredFruits); will be:

css
["apple", "cherry", "date"]

Keep in mind that the filter() method creates a new array and does not modify the original array. If you want to update the original array in-place, you can assign the result back to the original array like this:

javascript
fruits = filteredFruits;

This way, the fruits array will no longer contain the item you wanted to remove.

Comments