2017-02-06 3 views
0

内部オブジェクトと配列の値をunderscore.jsとreduceメソッドで合計しようとしています。しかし、私は何か間違っているように見えます。私の問題はどこですか?配列内にアンダースコアがあり、値が小さくなっているオブジェクトの合計値を返します。

let list = [{ title: 'one', time: 75 }, 
     { title: 'two', time: 200 }, 
     { title: 'three', time: 500 }] 

let sum = _.reduce(list, (f, s) => { 
    console.log(f.time); // this logs 75 
    f.time + s.time 
}) 

console.log(sum); // Cannot read property 'time' of undefined 
+0

は何かを返す必要が...実際にドキュメント – charlietfl

+0

を読んで、私はリターンを忘れてしまいました。しかし、私が戻ってhtmlにその値を表示しようとしたときにNaNが得られた – kirqe

+1

あなたはそれに初期値を与えるのを忘れてしまった。 '...、0)'を 'reduce'の最後に追加します。 –

答えて

6

listが既に配列であるため、ネイティブreduceを使用してください。

reduceコールバックは何かを返し、初期値を持つ必要があります。

これを試してみてください:

let list = [{ title: 'one', time: 75 }, 
 
     { title: 'two', time: 200 }, 
 
     { title: 'three', time: 500 }]; 
 

 
let sum = list.reduce((s, f) => { 
 
    return f.time + s; // return the sum of the accumulator and the current time. (as the the new accumulator) 
 
}, 0); // initial value of 0 
 

 
console.log(sum);

関連する問題