Here are some ways to remove a specific element from an array in JavaScript.
Using splice()
method
JavaScript
let array = [1, 2, 3, 4, 5];
let itemToRemove = 3;
// Find the index of the item to remove
let index = array.indexOf(itemToRemove);
// Remove the item using splice
if (index !== -1) {
array.splice(index, 1);
}
console.log(array); // Output: [1, 2, 4, 5]
Using filter()
method
JavaScript
let array = [1, 2, 3, 4, 5];
let itemToRemove = 3;
// Use filter to create a new array without the item to remove
array = array.filter(item => item !== itemToRemove);
console.log(array); // Output: [1, 2, 4, 5]
Using indexOf()
and splice()
together
JavaScript
let array = [1, 2, 3, 4, 5];
let itemToRemove = 3;
// Find the index of the item to remove and use splice
let index = array.indexOf(itemToRemove);
if (index !== -1) {
array.splice(index, 1);
}
console.log(array); // Output: [1, 2, 4, 5]