LoginSignup
2
0

More than 5 years have passed since last update.

reduceで配列の1つめの要素に処理が当たらない問題

Last updated at Posted at 2018-08-23

reduceで処理をしていて、1つ目の要素に処理があたらない問題が発生した。
例えば、以下の配列に、「フルーツ:」の文字列を付け足して、一つの文字列として生成したい場合。

期待するのは、"フルーツ:りんごフルーツ:ばなな,フルーツ:なし,フルーツ:ぶどう,"だが

js
const arr = ['りんご', 'ばなな', 'なし', 'ぶどう'];
const result = arr.reduce((previousValue, currentValue) => {
  const name = 'フルーツ:' + currentValue;
  return previousValue + name;
});
console.log(result);
//"りんごフルーツ:ばなな,フルーツ:なし,フルーツ:ぶどう,"

1回目の処理で’りんご’は'previousValue'に入り、'currentValue'にばななが入るため、'りんご'に処理は当たらない。

実はreduceは第二引数を取れることがわかった。

js
const arr = ['りんご', 'ばなな', 'なし', 'ぶどう'];
const result = arr.reduce((previousValue, currentValue) => {
  const name = 'フルーツ:' + currentValue + ',';
  return previousValue + name;
}, '');
console.log(result);
//"フルーツ:りんご,フルーツ:ばなな,フルーツ:なし,フルーツ:ぶどう,"

reduceの第2引数に空文字をいれることで、'previousValue'は空文字になり、'currentValue'に’りんご’が入ることができる。

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