LoginSignup
7
7

More than 5 years have passed since last update.

JavaScript:map,filterはreduceで書ける

Posted at

とよくいろんな文章に出てくる。こことか。
勉強のため自分で書いてみた。実用性は多分、ない。

map

  • 関数fと配列xsを引数にして
  • accの初期値を[]、配列の要素をeとして
  • f(e)を順次accに足していく
const rMap = f => xs => xs.reduce( (acc, e) => [...acc, f(e)], [])

filter

  • 関数fと配列xsを引数にして
  • accの初期値を[]、配列の要素をeとして
  • f(e)が真なら、eをaccの後に足す
const rFilter = f => xs => xs.reduce( (acc, e) => f(e) ? [...acc, e] : acc, [])

なるほど納得。reduce最強。

7
7
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
7
7