This post will discuss how to remove a specific element from an array in JavaScript.

There are several ways to remove a specific element from an array, depending on the index and the value of the element we want to remove. Here are some examples in JavaScript given an array and an element:

1. Using indexOf() and splice() functions

These functions allow us to find the index of the element we want to remove using indexOf(), and then remove that element using Array.splice(). The splice() function changes the contents of an array by removing existing elements and/or adding new elements. For example, if we have an array [1, 2, 3, 4, 5] and we want to remove the element 3, we can do:

Download  Run Code

 
If the element is not found in the array, the indexOf() function returns -1 and splice function call translates to arr.splice(-1, 1). Since negative index counts back from the end of the array, this will remove the last element from the array. To avoid this unwanted output, it is recommended to call splice() function only when the element is found in the array. For example, we can use something like this:

Download  Run Code

2. Using filter() function

The filter() function allows us to create a new array with all elements that pass a test implemented by a provided function. We can use it to filter out the element we want to remove from the original array. This will return a new array that contains all elements except the specified element. For example, if we have an array [1, 2, 3, 4, 5] and we want to remove the element 3, we can do like below. Based on the type of array, we can use the strict equality operator (===) in the callback function, or perform some custom comparison.

Download  Run Code

3. Using a for loop

This function allows us to iterate over the array and check each element for equality with the element we want to remove. To use it, we need to declare a variable that stores a new empty array. Then, we need to loop over the original array and push every element that is not equal to the specified element into the new array. We can then assign the original array to the new array or return it as a result. For instance:

Download  Run Code

That’s all about removing a specific element from an array in JavaScript.