5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

map, reduce, every, some,… 配列のループ処理の選び方チートシート

Last updated at Posted at 2019-04-20

対象

  • 初心者で、配列のループ処理について知りたい方
  • for によるループが飽きた方
  • 冗長なループ処理を簡略化したい方

tl;dr

  • for ループを関数によるループに置き換える方法
  • 目的別にどの関数を使えばよいのか

チートシート

chart1:

目的別の表です

table (1).png

chart2:

map / reduce の使い分けフローチャートです

flow_chart

だいぶ苦し紛れですが、ご容赦を…

見方

条件や一致する要素について得たい場合は、chart1 を見てください。

  • 縦列は、それぞれ一致条件などについて分類しています。
  • 横列は、返り値について分類しています。

例えば、

  • `["a", "b", "c", ..., "z"] という配列に対して、
  • "n" という要素に 一致するどうか(t/f) を得る

なら
includes を使う

  • [0, 1, 2, 3, ...] という配列に対して、
  • 偶数(2 で割り切れる)という 条件に合う 要素すべて 得る

なら
filter を使う

っていう感じです。

補足等

メソッドチェーン

map, filter (reduce1) に関しては、返り値として配列を返すので、メソッドチェーンができます。

const people = [{
  name: "Alice",
  sex: "female",
  age: 14
}, {
  name: "Bob",
  sex: "male",
  age: 15
}, { //...
  name: "Ellen",
  sex: "female",
  age: 21
}];
method_chain
people
  .filter(person => person.sex === "male")
  .filter(person => person.age <= 18)
  .map(person => person.name);

ただ、ループの回数が増える分、スピードが遅くなるので、場合によっては reduce に置き換えたほうが良いかもしれない。

reduce
people
  .reduce((acc, person) => {
    if(person.sex === "male" && person.age <= 18) {
      acc.push(person.name);
    }
    return acc;
  }, []);

私が実行した際は、 reduce に置き換えると実行時間がおよそ半分になった。
パフォーマンスを気にしないとか、読みやすさを重視するならば、メソッドチェーンを使えばいいと思う。

reduce 最強。

reduce さえあれば、
とりあえずなんでもできるんじゃないだろうかっていうぐらい強い。
詳しくは割愛。

そのうち reduce だけの書こうかな…

最後に一言

メソッドチェーンとかとうまく組み合わせながら、読みやすくかっこいいコードを書こう!

  1. 初期値として配列を指定し、ループごとに push するなど、配列を返すようにするときです。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?