Clue Mediator

Remove a specific item from an array in JavaScript

📅November 6, 2020

Today we’ll show you how to remove a specific item from an array in JavaScript. There are multiple ways to remove an element from an array using JavaScript.

You may check the few more articles related to the array.

Ways to remove a specific item from an array

  1. splice() method
  2. filter() method

1. splice() method

Here, In the first method, we will use the splice() method along with the indexOf() method. First, find the index of a specific item using the `indexOf()` method that you want to remove from an array. After that we have to remove that index using the `splice()` method.

const arr = [2, 3, 5, 9];

const index = arr.indexOf(3);
if (index > -1) {
  arr.splice(index, 1);
}

console.log(arr);
// Output: [2, 5, 9]

2. filter() method

Using the filter() method, we can easily remove the items from the list. It’s most preferable method to remove an item.

Example 1

let arr = [2, 3, 5, 9];

arr = arr.filter(x => x !== 3);
// Output: [2, 5, 9]

In the next example, we will see the array that contains the list of the object and remove the specific object from the list using the `filter()` method.

Example 2

let arr = [
  {
    userId: 1,
    id: 1,
    title: "delectus aut autem",
    completed: false
  },
  {
    userId: 2,
    id: 2,
    title: "quis ut nam facilis et officia qui",
    completed: false
  },
  {
    userId: 1,
    id: 3,
    title: "fugiat veniam minus",
    completed: false
  }
];

arr = arr.filter(x => x.userId !== 2);
/* Output:
[
  {
    userId: 1,
    id: 1,
    title: "delectus aut autem",
    completed: false
  },
  {
    userId: 1,
    id: 3,
    title: "fugiat veniam minus",
    completed: false
  }
]
*/

That’s it for today.
Thank you for reading. Happy Coding..!!