W3jar
360 words
2 minutes

How to Remove Items from Arrays by Value in JavaScript

Removing items from an array by value in JavaScript can be accomplished in several ways, depending on your requirements. Here are some common methods:

1. Using Array.prototype.filter()#

The filter method creates a new array with all elements that pass the test implemented by the provided function. This is a common and concise way to remove items by value.

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

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

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

2. Using Array.prototype.indexOf() and Array.prototype.splice()#

If you want to remove only the first occurrence of the value, you can use indexOf to find the index and then splice to remove the item.

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

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

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

3. Using Array.prototype.reduce()#

For more complex scenarios or when you want to create a new array while conditionally modifying it, you can use reduce.

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

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

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

4. Using Array.prototype.map() with Filtering#

If you need to transform the array while removing certain values, map in combination with filter might be useful.

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

const newArray = array
    .filter((item) => item !== valueToRemove)
    .map((item) => item); // .map here is optional if you are not transforming the array

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

5. Using Set for Removing Duplicates#

If your goal is to remove duplicates, you can use a Set, which automatically handles duplicate values.

const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = [...new Set(array)];

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

Notes#

  • filter creates a new array and does not modify the original array.
  • splice modifies the original array and returns the removed items.
  • For performance considerations, filter is generally preferred for removing multiple occurrences or when working with larger datasets.

Choose the method that best fits your needs based on whether you want to modify the original array or create a new one.