DEV Community

Prashant Sharma
Prashant Sharma

Posted on

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

To remove a specific item from an array in JavaScript, you can use various methods. Here are some common approaches:

1. Using filter()

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

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

const newArray = array.filter(item => item !== itemToRemove);

console.log(newArray); // [1, 2, 4, 5]
Enter fullscreen mode Exit fullscreen mode

2. Using splice()

If you know the index of the item, you can use splice() to remove it in place.

const array = [1, 2, 3, 4, 5];
const index = array.indexOf(3);

if (index !== -1) {
  array.splice(index, 1);
}

console.log(array); // [1, 2, 4, 5]
Enter fullscreen mode Exit fullscreen mode

3. Using findIndex() and splice()

If you need to remove an object from an array based on a condition:

const array = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

const index = array.findIndex(item => item.id === 2);

if (index !== -1) {
  array.splice(index, 1);
}

console.log(array);
// [{ id: 1, name: 'Alice' }, { id: 3, name: 'Charlie' }]
Enter fullscreen mode Exit fullscreen mode

Each of these methods works well depending on whether you're working with simple arrays or arrays of objects.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs