This post will discuss how to remove the first occurrence of a given value from an array in JavaScript.

1. Using Array.prototype.splice() function

The splice() method in JavaScript is often used to in-place add or remove elements from an array. The idea is to find an index of the element to be removed from an array and then remove that index using the splice() method.

Download  Run Code

 
Note that the indexOf() method returns -1 if the given value is not found in the array, and the splice would remove the last element of the array. To handle this case, it is recommended to check the presence of elements before calling the splice method, as demonstrated below:

Download  Run Code

2. Using ES6 Spread operator with slicing

With ES6, you can use the Spread operator with slicing to create a new array with the removed element. The idea is to split the array into two subarrays around the element which needs to be removed. Then merge both subarrays using the spread syntax. The following code example shows how to implement this.

Download  Run Code

3. Using Delete operator

The JavaScript delete operator removes a property from an object. If called on an array arr like delete arr[i], it replaces the value present at index i with a value undefined. In other words, it leaves an empty slot at index i. Note that using delete does not decrease the length of the array or update the index of the other elements. This is demonstrated below:

Download  Run Code

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