「こういう場合ってどれを使ったら良いんだろう」と毎回迷うので
まとめときます。
違い
| map | すべての要素に対して処理をして、すべての要素を返す | 
| reduce | すべての要素に対して処理をして、1つの要素を返す | 
| some | すべての要素のうち1つでも条件を満たしたらtrue | 
| every | すべての要素が条件を満たしたらtrue | 
| find | 最初に条件を満たした要素だけ返す | 
| filter | 条件を満たした要素をすべて返す | 
| forEach | 要素ごとにループを回す | 
map
すべての要素に対して「二乗する」という処理をして、すべての要素を返している例。
[1, 2, 3, 4, 5].map(
    (value,index) => value * value
);
//[1, 4, 9, 16, 25]
reduce
すべての要素の合計値を求める例。
[1, 2, 3, 4, 5].reduce(
    (acc, current) => acc + current, 0
);
//15
- コールバックの最後のループでreturnした値がreduceの戻り値になる。
- 第2引数の0は、初期値。
例えば以下のように書くと、出力結果が25になる。
[1, 2, 3, 4, 5].reduce(
    (acc, current) => acc + current, 10
);
//25
some
「それぞれの要素のうち、どれか一つでも10以上ならtrueを返す」という例。
[2, 3, 5, 7, 11].some(
    (element, index) => element >= 10
);
//true
every
「それぞれの要素の値がすべて10以上ならtrueを返す」という例。
[2, 3, 5, 7, 11].every(
    (element, index) => element >= 10
);
//false
find
「最初に7以上だった要素を返す」という例。
[2, 3, 5, 8, 11].find(
    (element,index) => element >= 7
);
//8
filter
「8以上の要素だけを返す」という例。
[1, 5, 8, 10, 2].filter(
    (value, index) => value >= 8
);
//[8, 10]
forEach
「それぞれの要素のインデックスと値を表示する」という例。
[10, 20, 30, 40, 50].forEach(
    (value, index) =>console.log(index + ":" + value)
);
//0:10
//1:20
//2:30
//3:40
//4:50
ベストな方法を選ぶ
重要なのは「どれを使うとシンプルに書けるか?」という点。
例えば、以下の4つはどれも「配列のすべての合計値を求めて表示する」をしているけど、①のreduceを使った書き方が一番シンプルになる。
//①
const total = [1, 2, 3, 4, 5].reduce((acc, current) => (acc + current), 0);
console.log(total);
//②
let total = 0;
[1, 2, 3, 4, 5].map((value) => (total += value));
console.log(total);
//③
let total = 0;
[1, 2, 3, 4, 5].forEach((value) => (total += value));
console.log(total);
//④
let total = 0;
for (const value of [1, 2, 3, 4, 5]) {
  total += value;
}
console.log(total);
短いコードは美しい😎
おわり
 
  
  
  
  
コメント