[JavaScript] Remove Elements from an Array (filter() is Convenient)

This article can be read in about 4 minutes.
PR

The purpose 

There are several ways to remove elements from a JavaScript Array, but most of them aren’t very convenient. (Methods like shift() and pop() have limited use cases, and I personally find slice() and splice() awkward.)

This article will show you how to use filter(), which is a versatile and generally more convenient method for removing elements.

PR

How to use

Overview of the filter() function

You pass a function as an argument to the filter() function.

The function you pass is called for each element in the Array.

If the function returns true, the element is kept; if it returns false, the element is removed.

The return value is a new Array containing only the elements that met your condition.

It’s important to note that the original Array is not modified.

Delete by index

The code to remove elements from an Array by their index is as follows:

const elements = ["element0", "element1", "element2", "element3", "element4"];

const result = elements.filter((element, index) => index != 2);

console.log(result);

Result:

Array ["element0", "element1", "element3", "element4"]

Explanation

The second argument passed to the filter function is the index of the element.

In the example above, the element with an index of 2 is removed.

Removing by Condition

The code to remove each element based on a condition is as follows:

const elements = ["element0", "element1", "element2", "element3", "element4"];

const result = elements.filter((element) => element != "element1");

console.log(result);

Result:

Array ["element0", "element2", "element3", "element4"]

Explanation

The first argument passed to the filter function is the element itself.

In the example above, elements are removed if they are equal to "element1".

PR

Reference

Array.prototype.filter() - JavaScript | MDN
filter() は Array インスタンスのメソッドで、指定された配列の中から指定された関数で実装されているテストに合格した要素だけを抽出したシャローコピーを作成します。

comment

Copied title and URL