What is the cleanest way to remove a specific element from an array in JavaScript?
’
Use array.filter() to create a clean new array without mutating the original, or combine indexOf() with splice() when you need to remove an item in place.
Non-Mutating Removal with .filter() (Recommended)
const languages = ["Python", "JavaScript", "C++", "SQL"];
// Removes "C++" without modifying the original array
const updated = languages.filter(item => item !== "C++");
console.log(updated); // ["Python", "JavaScript", "SQL"]
In-Place Removal with .splice()
const index = languages.indexOf("C++");
if (index !== -1) {
languages.splice(index, 1); // Mutates the array directly
}'
You must log in or register to comment.
