Removing Specific Array Items in Core JavaScript
Want to remove a particular value from an array effortlessly? Core JavaScript offers a straightforward approach.
Approach:
splice() Method:
The splice() method allows you to modify an array by removing existing elements or inserting new ones.
Example:
Consider the array [2, 5, 9]. To remove the value 5, follow these steps:
const array = [2, 5, 9]; const index = array.indexOf(5); // Find the index of the element if (index > -1) { // Only splice array if item is found array.splice(index, 1); // 2nd parameter removes only one item } // array = [2, 9]
In this example, the indexOf method finds the index of the value 5, which is 1. The splice method then removes the element at index 1, yielding the modified array [2, 9].
The above is the detailed content of How Can I Remove a Specific Item from an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!