0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

備忘録 Javascript reduceの使い方

Posted at

for文を多く書くとコードの見通しが悪いという事もありreduceを使ってみました。
処理速度については下記に諸先輩方が投稿されている記事があったので、下記をご参照ください。

for文での処理

var array = [0, 1, 2, 3, 4];
var sum = 0;

for(var i = 0; i < array.length; i++){
  sum += array[i];
}

console.log(sum); // 10

reduceでの処理①

var array = [0, 1, 2, 3, 4];

var result = array.reduce(function(accumlator, currentValue, currentIndex, array){
  return accumlator + currentValue;
})

console.log(result); // 10

reduce1.PNG

reduceでの処理②

var array = [0, 1, 2, 3, 4];

var result = array.reduce(function(accumlator, currentValue){
  return accumlator + currentValue;
},10);

console.log(result); //20

reduce2.PNG

※第二引数に初期値を設定する事ができる。(今回の場合は、10を設定)

reduceでの処理③

APIのレスポンスとかで良くありそうな、配列の中にjsonオブジェクトが入った形を処理してみる。
ポイントは第二引数に0を渡すことで初期値を設定している事!

var items = [
  {
    name: 'pen',
    price: 100,
    quantity: 2
  },
  {
    name: 'note',
    price: 200,
    quantity: 3
  },
  {
    name: 'eraser',
    price: 50,
    quantity: 1,
  }
]

var result = items.reduce(function(accumlator, currentValue){
  console.log(accumlator);
  console.log(currentValue);
  return accumlator + (currentValue.price * currentValue.quantity);
},0);

console.log(result); //850

↑のconsole.log(accumlator)とconsole.log(currentValue)とconsole.log(result)の結果

0
{ name: 'pen', price: 100, quantity: 2 }
200
{ name: 'note', price: 200, quantity: 3 }
800
{ name: 'eraser', price: 50, quantity: 1 }
850

参考
https://qiita.com/Hibikine_Kage/items/660392270c466b3f9805
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?