戻る

filter()メソッド
trueを返す要素のみを新しい配列に含めます。

[サンプル]
copy
const ary1 = [10, 20, 30, 40, 50];

//4の剰余が0のみ(4で割り切れる数字のみ)を抽出する
const ary2 = ary1.filter(function(ary1) 
{
	return ary1 % 4 === 0;
});



console.log(ary1);//[10, 20, 30, 40, 50]
console.log(ary2);//[20, 40]

配列の要素を特定の条件で絞り込み、新しい配列を生成するメソッドです。
このメソッドは、コールバック関数を受け取ります。
trueを返す要素のみを新しい配列に含めます。
true要素は新しい配列に含められます。
false要素は新しい配列に含められません。
配列のすべての要素に対してコールバック関数を実行するため、
要素数が多い場合は処理に時間がかかる場合があります。

コールバック関数内で副作用 (例えば、グローバル変数の変更など) を行うと、
予期しない結果になる可能性があります。

copy
const ary3 = [10, 20, 30, 40, 50];
const removeIndex = 2;
//removeIndexに対応する要素を除いた新しい配列を生成します
const ary4 = ary3.filter((_, i) => i !== removeIndex);

console.log(ary3);//[10, 20, 30, 40, 50]
console.log(ary4);//[10, 20, 40, 50]
(_, i) =>
アロー関数で、filterメソッドに渡されるコールバック関数です。
_filterメソッドは、要素の値とインデックスの両方をコールバック関数に渡します。
しかし、このサンプルでは値は使用しないため`_`で無視しています。
i要素のインデックスを表します。
i !== removeIndex
コールバック関数の条件式です。
現在の要素のインデックスiとremoveIndexと等しくない条件を判定しています。
条件に一致した場合はtrueが返り、そのデータのみを新しい配列に格納しています。



戻る
back

filter() method
Only elements that return true will be included in the new array.

[sample]
copy
const ary1 = [10, 20, 30, 40, 50];

//Extract only numbers that are divisible by 4 (0 modulo 4)
const ary2 = ary1.filter(function(ary1) 
{
	return ary1 % 4 === 0;
});



console.log(ary1);//[10, 20, 30, 40, 50]
console.log(ary2);//[20, 40]

This method filters array elements based on specific criteria and generates a new array.
This method accepts a callback function.
Only elements that return true are included in the new array.
trueElements are included in the new array.
falseElements are not included in the new array.
Since the callback function is executed for every element in the array,
processing may take some time if there are a large number of elements.

Performing side effects within a callback function (such as modifying a global variable) may
cause unexpected results.

copy
const ary3 = [10, 20, 30, 40, 50];
const removeIndex = 2;
//Creates a new array without the element corresponding to removeIndex.
const ary4 = ary3.filter((_, i) => i !== removeIndex);

console.log(ary3);//[10, 20, 30, 40, 50]
console.log(ary4);//[10, 20, 40, 50]
(_, i) =>
This is an arrow function, a callback function passed to the filter method.
_The filter method passes both the element's value and index to the callback function.
However, since the value is not used in this example, it is ignored with `_`.
iRepresents the element's index.
i !== removeIndex
This is the condition expression for the callback function.
It checks whether the current element index i is not equal to removeIndex.
If the condition is met, true is returned, and only that data is stored in the new array.




back



著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。