JavaScript Code

How to remove specific item from an array using JavaScript?


Problem Statement

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);



copyright @2022