HomeIntegrated Development Environment (IDE)How can I remove a specific item from an array in JavaScript?

How can I remove a specific item from an array in JavaScript?

There are several ways in which you may use JavaScript to delete a specific item from an array. The method you use may vary depending on the JavaScript version you’re using and your unique requirements. Here are a few such techniques:

Using the splice() function

You can add, remove, or alter items in an array with the splice() function.

let aarrray = [1, 2, 3, 4, 5];
let itemToRemove = 3;

// Determine the removed item's index.
let index = aarrray.indexOf(itemToRemove);

if (index !== -1) {
// Use splice to remove the item at the specified index
aarrray.splice(index, 1);
}

console.log(aarrray); // [1, 2, 4, 5]

Using the filter() function

A new array containing all elements that pass a test supplied by a callback function is created using the filter() method.

let aarrray = [1, 2, 3, 4, 5];
let itemToRemove = 3;

//Make a new array with the item to be removed.
let newArray = aarrray.filter(item => item !== itemToRemove);

console.log(newArray); // [1, 2, 4, 5]

Using ‘for‘ loop

Another option is to go over the array using a for loop, copying the elements you wish to keep to a new array.

let aarrray = [1, 2, 3, 4, 5];
let itemToRemove = 3;
let newArray = [];

for (let i = 0; i < aarrray.length; i++) {
if (aarrray[i] !== itemToRemove) {
newArray.push(aarrray[i]);
}
}

console.log(newArray); // [1, 2, 4, 5]

Applying the slice() and indexOf() methods:

Using indexOf(), you may determine the index of the item to be deleted. Next, you can slice the array to produce a new array before and after the deleted item.

let aarrray = [1, 2, 3, 4, 5];
let itemToRemove = 3;

let index = aarrray.indexOf(itemToRemove);

if (index !== -1) {
let newArray = aarrray.slice(0, index).concat(aarrray.slice(index + 1));
console.log(newArray); // [1, 2, 4, 5]
}

Spread operators (available in ES6 and later):

The spread operator in contemporary JavaScript allows you to build a new array sans the item you want to delete.

let aarrray = [1, 2, 3, 4, 5];
let itemToRemove = 3;

let newArray = aarrray.filter(item => item !== itemToRemove);
console.log(newArray); // [1, 2, 4, 5]

There are several JavaScript ways to remove a particular element from an array. The approach you use may vary depending on the JavaScript version you are using and your particular use case.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Random Picks

Most Popular