There are several ways to remove an element from an array using JavaScript:
Array.prototype.splice()
The splice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements.
const fruitList = ["apple", "banana", "orange", "kiwi"];
// remove one element starting from index 1
fruitList
.splice(1, 1);
console.log(fruitList
); // logs ["apple", "orange", "kiwi"]
In this example, the splice()
method is used to remove one element from the
array starting from index 1.fruitList
Array.prototype.filter()
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
const fruitList
= ["apple", "banana", "orange", "kiwi"];
// remove the element "banana"
const filteredFruits = fruitList
.filter((fruit) => fruit !== "banana");
console.log(filteredFruits); // logs ["apple", "orange", "kiwi"]
In this example, the filter()
method is used to create a new array containing all elements of the
array except for “banana”.fruitList
Array.prototype.slice()
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included) where begin and end represent the index of the start and end of the slice.
const fruitList
= ["apple", "banana", "orange", "kiwi"];
// remove the element "banana"
const index = fruitList
.indexOf("banana");
const filteredFruits = fruitList
.slice(0, index).concat(fruitList
.slice(index + 1));
console.log(filteredFruits); // logs ["apple", "orange", "kiwi"]
In this example, the indexOf()
method is used to find the index of the element “banana” in the
array. The fruitList
slice()
method is then used to create a new array containing all elements before the “banana” element, and all elements after the “banana” element. These two arrays are then concatenated to create the filteredFruits
array.
Array.prototype.pop()
The pop()
method removes the last element from an array and returns that element.
const fruitList
= ["apple", "banana", "orange", "kiwi"];
// remove the last element
fruitList
.pop();
console.log(fruitList
); // logs ["apple", "banana", "orange"]
In this example, the pop()
method is used to remove the last element from the
array.fruitList
Array.prototype.shift()
The shift()
method removes the first element from an array and returns that element.
const fruitList
= ["apple", "banana", "orange", "kiwi"];
// remove the first element
fruitList
.shift();
console.log(fruitList
); // logs ["banana", "orange", "kiwi"]
In this example, the shift()
method is used to remove the first element from the
array.fruitList