LoginSignup
1
0

More than 1 year has passed since last update.

【JavaScript】配列の操作(forEach map filter reduce)の使い方

Posted at

初投稿

アウトプットが苦手な自分が練習の一環として記事を書いてみる。

第一回目はJavaScript配列の操作(forEach map filter reduce)の使い方について書いていく。

forEach

配列の各要素に対して関数を1つずつ実行するメソッド
※後述するmapやfilterと違い新しい配列を作成しない。

forEach
const arr = [10, 20, 30, 40, 50];

arr.forEach(function(elm) {
    console.log(elm);
});
// 実行結果
// 10
// 20
// 30
// 40
// 50

map

配列の各要素に対して関数を1つずつ実行し、戻り値を元に新しい配列を作成するメソッド

map
const arr = [10, 20, 30, 40, 50];

const result = arr.map(function(elm) {
    return elm * 2;
});

console.log(result);
// 実行結果
// [ 20, 40, 60, 80, 100 ]

filter

配列の各要素に対して関数を1つずつ実行し、戻り値を元に新しい配列を作成するメソッド

mapと違い、戻り値が「true」の要素のみで配列を作成する。
※作成した配列の値は関数実行時の要素の値が格納される。

filter
const arr = [10, 20, 30, 40, 50];

const result = arr.filter(function(elm) {
    return elm > 29;
});

console.log(result);
// 実行結果
// [ 30, 40, 50 ]

reduce

配列の各要素に対して関数を1つずつ実行し1つの値を取得するメソッド
※使ったことなかったので使い方を調べた

reduce
const arr = [10, 20, 30, 40, 50];

const result = arr.reduce(function(a, b) {
    return a + b;
});

console.log(result);
// 実行結果
// 150

ソースを見ればなんとなくやっていることが分かるが念の為、実行時のイメージを作成。

関数実行回数 a b 返り値
1回目 10 20 30
2回目 30 30 60
3回目 60 40 100
4回目 100 50 150

1回目のaには配列の最初の要素「10」が入り、bには次の要素「20」が入る。
2回目のaには1回目の返り値「30」が入りbには1回目のbの次の要素(今回は)「30」が入る。
以降は配列の要素分同じように繰り返し、最後の返り値の「150」がresultに代入される動きとなる。

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