Home >Web Front-end >JS Tutorial >How Do I Remove an Element from a JavaScript Array by Value?
Removing Items from an Array by Value
When working with arrays in JavaScript, it is often necessary to remove specific items from them. Unlike the splice() method, which removes elements based on their position, there is a need for a method that can remove elements based on their values.
To achieve this, you can utilize the indexOf() method to find the index of the desired element in the array. This method returns the first occurrence of the element and -1 if it is not found.
Once the index is obtained, you can use the splice() method to remove the element from the array. The splice() method takes two parameters:
By combining indexOf() and splice(), you can effectively remove items from an array based on their values:
const array = ['three', 'seven', 'eleven']; const item = 'seven'; const index = array.indexOf(item); if (index !== -1) { array.splice(index, 1); } console.log(array); // Output: ['three', 'eleven']
This approach is straightforward and works efficiently for arrays of any size. It is also widely supported by modern browsers and JavaScript environments.
The above is the detailed content of How Do I Remove an Element from a JavaScript Array by Value?. For more information, please follow other related articles on the PHP Chinese website!