How do I remove an item from an array by its value in JavaScript?
Alex K
alex k profile pic

In JavaScript, there are several ways to remove an item from an array based on its value. Here are a few common approaches: 1. Using thesplice() method: - Thesplice() method allows you to modify an array by adding or removing elements. By specifying the index of the element you want to remove and the number of elements to remove (which is 1 in this case), you can remove the item from the array.

1
2
3
4
5
6
7
8

   const array = [1, 2, 3, 4, 5];
   const value = 3;
   const index = array.indexOf(value);
   if (index > -1) {
     array.splice(index, 1);
   }
   

In this example,array.indexOf(value) finds the index of the element with the value3, andarray.splice(index, 1) removes one element starting from that index. Note that if the element is not found in the array,indexOf() returns-1, and thesplice() operation is not performed. 2. Using thefilter() method: - Thefilter() method creates a new array containing all elements that pass a certain condition. By using a filtering condition that excludes the value you want to remove, you can effectively remove the item from the array.

1
2
3
4
5

   const array = [1, 2, 3, 4, 5];
   const value = 3;
   const filteredArray = array.filter((item) => item !== value);
   

Here,array.filter((item) => item !== value) creates a new array by filtering out all elements that are not equal to3, effectively removing the item from the array. Note thatfilter() does not modify the original array; it returns a new array with the filtered elements. 3. Using theindexOf() method with theslice() method: - By combining theindexOf() method and theslice() method, you can create a new array that excludes the element you want to remove.

1
2
3
4
5
6

   const array = [1, 2, 3, 4, 5];
   const value = 3;
   const index = array.indexOf(value);
   const newArray = array.slice(0, index).concat(array.slice(index + 1));
   

In this example,array.indexOf(value) finds the index of the element with the value3. Then,array.slice(0, index) creates a new array containing the elements before the index, andarray.slice(index + 1) creates a new array containing the elements after the index. Finally,concat() is used to merge the two arrays intonewArray. Note that this method does not modify the original array; it creates a new array with the desired elements. Choose the method that best suits your requirements and the specific context in which you are working. Thesplice() method allows you to directly modify the original array, while thefilter() method and the combination ofindexOf() andslice() methods create new arrays without modifying the original one.