2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

配列の値を一つずつ取得して計算したい

Posted at

はじめに

オブジェクトを要素に持つ配列の操作でつまったのでまとめてみました。

問題

オブジェクトを要素に持つ配列の時間だけを取得して合計時間を出したい。

const records = [
    { title: "タイトル1", time: 1},
    { title: "タイトル2", time: 3},
    { title: "タイトル3", time: 5}
]

解決方法

reduceを使用する

const answer = records.reduce(
    (accumulator, currentValue) => accumulator + parseInt(currentValue.time), 0
);

reduce関数とは

reduce(callbackFn, initialValue)
callbackFn

mdnより抜粋
配列の各要素に対して実行される関数。その返値は、次に callbackFn を呼び出す際の accumulator 引数の値になります。最後の呼び出しでは、返値は reduce() の返値となります。この関数は以下の引数で呼び出されます。

(accumulator, currentValue) => accumulator + parseInt(currentValue.time), 0

accumulator
前回の callbackFn の呼び出し結果の値を格納する。

currentValue
現在の要素の値です。オブジェクトなのでプロパティまで指定する。

initialValue

省略可、callbackFnで配列の最初の要素を呼び出す時に指定する初期値

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?