[JavaScript]Remove elements from an array (filter() is useful for this).

この記事は約4分で読めます。
スポンサーリンク

Things I want to do

There are several ways to remove elements from an array in JavaScript, but most of them are not very user-friendly.

(Shift and Pop have limited uses, and I personally find Slice and Splice difficult to use.)

This section introduces how to use the filter() function, which can be used in a general way.

スポンサーリンク

How to use

filter function overview

The filter function takes a function as an argument.

The function you pass will be called for each element in the array.

If the function returns true, the element is retained; if it returns false, the element is deleted.

The return value is an Array from which elements have been removed according to the condition.

Please note that the original Array will not be modified.

Deleted in Index

The code to delete an element using an array 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 of the function passed to `filter` is the index of the element.

In the example above, the element with index 2 is deleted.

Delete by condition

The following is the code to delete each element based on a condition.

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 of the function passed to `filter` is the element.

In the example above, the element is deleted if it is named ‘element1’.

スポンサーリンク

Websites I used as references

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

コメント

タイトルとURLをコピーしました