Summing Arrays In Javascript Using D3.nest() Part Ii
Solution 1:
Hasn't occurred to me till now that a single element array will not execute the function; but it makes sense, because you're using with a single param:
[].reduce(function(prev, curr, i, arr) {});// <-- function is the only param
When used with a single param, the behavior is that the first time the function is executed, i
equals 1 (not 0), and prev
and curr
are the first and second elements of the array. Since you only have one element, there's no way to call it in this form.
If you use reduce with a 2nd param:
[].reduce(function(prev, curr, i, arr) {}, { foo:'bar' });// <-- 2nd param {foo:bar}
it does actually call the function, with the first call passing i
equal to 0 and prev
equaling { foo:'bar' }
.
So I guess you have 2 options:
Either modify it to pass a 2nd param, which in your case would need to be
{ values:[0,0] }
(and that hardcodes the fact thatvalues
is always 2 elements, which will cause an issue if it's longer).Check if
group.length == 1
and if so,return group
, instead of calling reduce.
Post a Comment for "Summing Arrays In Javascript Using D3.nest() Part Ii"