How to remove a specific item from an array in JavaScript?

1. Using filter

The filter method creates a new array that excludes the specific item(s).

Example:

const array = [1, 2, 3, 4, 5];
const itemToRemove = 3;

// Create a new array excluding the item
const result = array.filter(item => item !== itemToRemove);

console.log(result); // Output: [1, 2, 4, 5]

2. Using splice

The splice method modifies the original array by removing elements at a specific index.

Steps:

  1. Find the index of the item using indexOf.
  2. Use splice to remove the item.

Example:

const array = [1, 2, 3, 4, 5];
const itemToRemove = 3;

// Find the index of the item
const index = array.indexOf(itemToRemove);

if (index !== -1) {
// Remove the item at the found index
array.splice(index, 1);
}

console.log(array); // Output: [1, 2, 4, 5]

3. Using findIndex with splice

If you need to match complex conditions, use findIndex to locate the item.

Example:

const array = [{ id: 1 }, { id: 2 }, { id: 3 }];
const itemToRemove = 2;

// Find index based on a condition
const index = array.findIndex(item => item.id === itemToRemove);

if (index !== -1) {
// Remove the item
array.splice(index, 1);
}

console.log(array); // Output: [{ id: 1 }, { id: 3 }]

4. Using reduce

The reduce method allows you to construct a new array by including only the items you want.

Example:

const array = [1, 2, 3, 4, 5];
const itemToRemove = 3;

const result = array.reduce((acc, item) => {
if (item !== itemToRemove) {
acc.push(item);
}
return acc;
}, []);

console.log(result); // Output: [1, 2, 4, 5]

5. Using Set for Unique Items

If your array contains unique items and you want to remove a specific item:

Example:

Editconst array = [1, 2, 3, 4, 5];
const itemToRemove = 3;

const set = new Set(array);
set.delete(itemToRemove);

const result = Array.from(set);

console.log(result); // Output: [1, 2, 4, 5]

6. Using slice to Remove an Item Without Modifying the Original Array

If you know the index of the item:

Example:

const array = [1, 2, 3, 4, 5];
const indexToRemove = 2;

// Use slice to create a new array excluding the item
const result = [...array.slice(0, indexToRemove), ...array.slice(indexToRemove + 1)];

console.log(result); // Output: [1, 2, 4, 5]

When to Use Each Method

  • filter: Best for creating a new array while excluding items based on a condition.
  • splice: Ideal for directly modifying the original array.
  • findIndex + splice: Use for complex conditions.
  • reduce: Useful for advanced transformations while filtering items.
  • slice: Creates a new array without modifying the original when the index is known.

No images available.