In JavaScript, you can remove a specific element from an array using the splice() method. The splice() method allows you to add or remove elements from an array by specifying the starting index and the number of elements to remove.

For example, to remove the element with the value “banana” from the following array:

var fruits = ["apple", "banana", "cherry"];

You can use the indexOf() method to find the index of the element you want to remove, and then use the splice() method to remove it.

var index = fruits.indexOf("banana");
if (index !== -1) {
    fruits.splice(index, 1);
}
console.log(fruits); // ["apple", "cherry"]

Another way to remove specific element from array is using filter method.

var fruits = ["apple", "banana", "cherry"];
var newFruits = fruits.filter(item => item !== "banana");
console.log(newFruits); // ["apple", "cherry"]

You can also use the findIndex method to find the index of the element you want to remove, and then use the splice method to remove it.

var fruits = ["apple", "banana", "cherry"];
var index = fruits.findIndex(item => item === "banana");
if (index !== -1) {
    fruits.splice(index, 1);
}
console.log(fruits); // ["apple", "cherry"]

Please be aware that the splice() method modifies the original array, so if you want to keep the original array intact you will have to create a new array with the removed element.

You can use any of the above methods to remove a specific element from an array in JavaScript.

Also Read:

Categorized in: