Remove specific item from an array in JavaScript
In this tutorial, you are given an array. Write a JavaScript program to remove specific item from the array.
Solution
To remove a specific item from given array, we can use Array.filter() method. Call filter()
method on the given array, and pass a function that returns false
for the specific item, or true
otherwise. filter()
method returns a new array with the specified item removed from the contents of original array.
Program
1. Remove item "apple"
from the fruits
array.
function removeSpecificElement(item) {
if (item != this) {
return true;
} else {
return false;
}
}
names = ["apple", "banana", "apple", "cherry"];
output = names.filter(removeSpecificElement, "apple");
console.log(output);