A cleaner way to accomplish this is by providing an initial value as the second argument to reduce
:
var arr = [{x:1}, {x:2}, {x:4}];
var result = arr.reduce(function (acc, obj) { return acc + obj.x; }, 0);
console.log(result); // 7
The first time the anonymous function is called, it gets called with (0, {x: 1})
and returns 0 + 1 = 1
. The next time, it gets called with (1, {x: 2})
and returns 1 + 2 = 3
. It’s then called with (3, {x: 4})
, finally returning 7
.
This also handles the case where the array is empty, returning 0
.