/

How to Remove an Item from an Array in JavaScript

How to Remove an Item from an Array in JavaScript

JavaScript provides various methods to remove an item from an array. In this article, we will explore the canonical approach as well as other options using plain JavaScript.

Here are a few ways to remove an item from an array using JavaScript:

  1. By Index: If you know the index of the item you want to remove, you can use the slice() method to create a new array without mutating the original one.

    1
    2
    3
    4
    const items = ['a', 'b', 'c', 'd', 'e', 'f'];
    const i = 2;
    const filteredItems = items.slice(0, i).concat(items.slice(i + 1, items.length));
    // Result: ["a", "b", "d", "e", "f"]

    Here, we create a new array by concatenating two slices of the original array before and after the index to be removed.

  2. By Value: If you know the value of the item you want to remove, you can use the filter() method for a more declarative approach.

    1
    2
    3
    4
    const items = ['a', 'b', 'c', 'd', 'e', 'f'];
    const valueToRemove = 'c';
    const filteredItems = items.filter(item => item !== valueToRemove);
    // Result: ["a", "b", "d", "e", "f"]

    This approach uses arrow functions introduced in ES6. You can also use traditional functions for older browser support or transpile the code using Babel for wider compatibility.

  3. Removing Multiple Items:

    • By Index: To remove multiple items using their indexes, you can create a function that removes items one by one.

      1
      2
      3
      4
      5
      6
      7
      8
      const items = ['a', 'b', 'c', 'd', 'e', 'f'];

      const removeItem = (items, i) =>
      items.slice(0, i - 1).concat(items.slice(i, items.length));

      let filteredItems = removeItem(items, 3);
      filteredItems = removeItem(filteredItems, 5);
      // Result: ["a", "b", "d", "e"]
    • By Value: To remove multiple items using their values, you can search for inclusion inside the callback function.

      1
      2
      3
      4
      const items = ['a', 'b', 'c', 'd', 'e', 'f'];
      const valuesToRemove = ['c', 'd'];
      const filteredItems = items.filter(item => !valuesToRemove.includes(item));
      // Result: ["a", "b", "e", "f"]

It is important to avoid mutating the original array. The splice() method should be avoided as it mutates the original array.

tags: [“JavaScript”, “array manipulation”, “remove item”, “filter”, “splice”]