【JavaScript】Array.prototype.reduce()

  • このエントリーをはてなブックマークに追加

Array.prototype.reduce()はややこしいな。

簡単な使い方
reduceメソッドで配列の中の数値をすべて足して合計値を求める。
reduceメソッドで配列の中の文字列をすべて連結した文字列を作る。
配列の中の文字列を連結したいならjoinメソッド使った方が記述内容も少なくて分かりやすいな。

reduce (他)を減らす

配列の中の数値を全部合計する処理にreduceメソッド使えるな。
しかし、なんでreduceという名前なんだ?「減らす」とう意味だよな。



    let numbers = [1,2,3,4,5,6,7,8,9,10];
    let strings = ['あいうえお','かきくけこ','さしすせそ'];
    
    let result = numbers.reduce(function(a, b) {
      return a + b;
    });

    let result2 = strings.reduce(function(a, b) {
      return a + b;
    });

    console.log(result);
    console.log("typeof result = " + typeof result);
    
    console.log(result2);
    console.log("typeof result2 = " + typeof result2);
    
    let result3 = strings.join('');
    
    console.log(result3);
    console.log("typeof result3 = " + typeof result2);
    
/*

55
typeof result = number
あいうえおかきくけこさしすせそ
typeof result2 = string
あいうえおかきくけこさしすせそ
typeof result3 = string

*/

アロー関数式も使える。初期値に関しては、空の配列を初期値なしで実行するとエラーになったり、予期せぬ実行結果になったりする可能性があるため、初期値は設定した方がいい。



    let numbers = [1,2,3,4,5,6,7,8,9,10];
    let strings = ['あいうえお','かきくけこ','さしすせそ'];

    let result = numbers.reduce(( sum, element ) => sum + element,0);
    console.log(result);
    console.log("typeof result = " + typeof result);
    
    
    let result2 = strings.reduce(( sum, element ) => sum + element,"");
    console.log(result2);
    console.log("typeof result2 = " + typeof result2);
    
/*

55
typeof result = number
あいうえおかきくけこさしすせそ
typeof result2 = string

*/




【JavaScript】Array.prototype.concatメソッドとArray.prototype.reduce()メソッド (attacktube.com)
【JavaScript入門】初心者でも分かるreduce()の使い方とサンプル例まとめ | 侍エンジニアブログ (sejuku.net) ExternalLink
【JavaScript基礎】Array.prototype.reduce() をしっかり理解する&サンプル集 – KDE BLOG (hateblo.jp) ExternalLink

  • このエントリーをはてなブックマークに追加

SNSでもご購読できます。

コメントを残す

*