Remove specific values from an array in JavaScript
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Array.prototype.remove = function(value) { this.splice(this.indexOf(value), 1); } var arr = [1, 2, 4, 2, 5]; var item = 2; arr.remove(item); console.log(arr); /* Output: [ 1, 4, 2, 5 ] */ |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Array.prototype.remove = function(value) { var index = this.indexOf(value); if (index !== -1) { this.splice(index, 1); } } var arr = [1, 2, 4, 2, 5]; var item = 2; arr.remove(item); console.log(arr); /* Output: [ 1, 4, 2, 5 ] */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function remove(arr, item) { var index = arr.indexOf(item); return [ // part of the array before the given item ...arr.slice(0, index), // part of the array after the given item ...arr.slice(index + 1) ]; } var arr = [1, 2, 4, 2, 5]; var item = 2; arr = remove(arr, item); console.log(arr); /* Output: [ 1, 4, 2, 5 ] */ |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var arr = [1, 2, 4, 2, 5]; var item = 2; var index = arr.indexOf(item); if (index !== -1) { delete arr[index]; } console.log(arr); /* Output: [ 1, <1 empty item>, 4, 2, 5 ] */ |
That’s all about removing specific values from an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)