To remove a specific item from an array in JavaScript, you can use the splice() method. The splice() method modifies the original array and returns an array containing the removed items.
Here's an example of how to remove a specific item from an array:
let myArray = ['apple', 'banana', 'orange', 'pear'];
// find the index of the item you want to remove
let index = myArray.indexOf('orange');
// use the splice method to remove the item at the index
myArray.splice(index, 1);
console.log(myArray); // Output: ['apple', 'banana', 'pear']
In the example above, we first use the indexOf() method to find the index of the item we want to remove. Then, we pass that index and the number 1 as arguments to the splice() method. This removes one item starting at the specified index.
Note that if the item you want to remove appears multiple times in the array, splice() will only remove the first occurrence. If you want to remove all occurrences, you would need to use a loop or a different approach.
Comments (0)