LoginSignup
0
0

More than 3 years have passed since last update.

[Javascript]reduceの第2引数(初期化)の使い所を理解する[なにが返ってくるんじゃい2]

Last updated at Posted at 2020-07-18

目的

  • reduceの第2引数の要否を判断できるようになる。

今日やること

昨日の投稿でmapとfilterの使い分けを理解した。
今日は、その中で疑問点に上がったreduceの第2引数要否について理解を深める。

reduceとは

reduce.js

 collection.reduce = (iterator, accumulator) => {
    let i =0
    collection.each((value, index, collection) => {
      if (accumulator === undefined && i==0) {
        accumulator = value;
        i++
      } else {
        accumulator = iterator(accumulator, value, index, collection);
      }
    });
    return accumulator
  };

昨日の投稿から抜粋。

不要なとき
avgMaxCP()=>{   
return allPokemon.filter(pokemon => pokemon.MaxCP)
    .reduce((acc, pokemon) => acc + Number(pokemon.MaxCP),0) 
  }

filter処理後にMaxCP(オブジェクト)を要素にもつ配列している。
そして、reduceに渡している。そのためreduceの第二引数には0をいれる必要がある。
そうしなければ、配列の最初の要素はaccに入りNumberで数字化できず結果NaNになる。
ただし、二つ目の要素からはできる。

必要なとき
  avgMaxCP () => {
   const hasMaxCP = allPokemon.map(pokemon => {
        return pokemon.MaxCP
      });
      const a = hasMaxCP.filter(maxcp => {
        return maxcp
      });
      let sum = a.reduce((acc, cur) => {
        return acc + cur
      });
      return sum 
    },

map処理後に、全てのポケモンをMaxCPに変形した。[1,2,3,undefined・・・]のイメージ。
(ポケモンのオブジェクトではない)
filterに上記の配列を渡して処理し、MaxCPをもつ要素だけの配列になる。
今、aには数字のみが入っているので、Numberやreduceの第二引数のような処理は不要になる。

結論 第二引数 = 初期化は、渡した配列の最初の要素が想定通りであれば不要。

array.reduce((a,b)=>a+Number(b)のように数字化して処理するときに、最初の要素が数字化(変形)されているか確認すること。

その他、下記の記事も見つけた。
reduce()はArrayにて最強……おぼえておけ。
意外と知られていないJavaScriptのreduceの使用方法

想像以上にreduceは万能そう(!)なので、reduce利用シーンを後日まとめる。

0
0
2

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