LoginSignup
15
14

More than 5 years have passed since last update.

JavaScriptのmap / filter / reduceっていつも雰囲気で書いてるけど実際どんな挙動するんだっけ?

Last updated at Posted at 2018-02-12

miyachi(@_38ch)です。
for文で無理やり配列操作するよりスマートな方法をしっかり覚えておきたい。
そしてアローで書きたい。

filter

配列の中から条件に合うものだけを抽出する。

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

words配列の中から6文字以上のものだけを抽出しています。

map

Pythonで言うところのlambda的な書き方。配列の各要素に対して、関数を呼び出し、その結果から新しい配列を作成する。

var array1 = [1, 4, 9, 16];

const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

array1の各要素を2倍して新しい配列を作成している。

var users = [{id: 0, name: 'Mike'},
            {id: 1, name: 'John'},
            {id: 2, name: 'Tom'}];

var names = users.map(user => user.name);

console.log(names);
// expected output: Array ['Mike', 'John', 'Tom']

オブジェクト配列から特定のキーのみを指定して配列を作ることも可能。

reduce

累積値を求める時とかに使う?

var array = [1,2,3]
var reduced = array.reduce((cumulativeValue, element) => cumulativeValue + element);

console.log(reduced);
// expected output: 6(1~3の累積値)

とりあえずこの三つは覚えておきましょう。

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