How can I remove a specific item from an array in JavaScript?

 There are several method to remove a specific item from an array in JavaScript. These are most common used methods:

Using ' splice( ) ' method :

The 'spice( )' method return original array by adding or removing item at a specified index.

Code :
let array = [1, 2, 3, 4, 5];
let itemToRemove = 3; // The item you want to remove
let index = array.indexOf(itemToRemove);

if (index !== -1) {
    array.splice(index, 1); // Remove 1 element at the found index
}

console.log(array); // The array without the removed item

If you want to remove more than one element from an arrays at the index element.  

Code :
let array = [1, 2, 3, 4, 5];
let itemToRemove = 3; // The item you want to remove
let index = array.indexOf(itemToRemove);
let howMany = 3;

if (index !== -1) {
    array.splice(index, howMany); // Remove 3 element at the found index
}

console.log(array); // The array without the removed item

you can not used values in negatives in howMany


' filter( )' method :

The ' filter( )' method creates a new arrays which have all elements which pass a provided test function. You can also create a new arrays with the same elements. 

Code :
const people = ["Alice", "Bob", "Charlie", "David", "Eve"];
const itemToRemove = "Eve";
const newArray = people.filter(item => item !== itemToRemove);
console.log(newArray); // ["Alice", "Bob", "Charlie", "David"];

In this code, we have array of people which contain 5 elements and we want to remove Eve from it.  In this method you don't need index of element, you only need the elements and pass through filter method where filter check every elements from itemToRemove if item itemToRemove .Filter method did not copy element in our new arrays.


   

Comments