Summing Arrays in JavaScript Using d3.nest () Part II

I recently posted this question about summing arrays in JavaScript using d3.nest ()

I got a good solution (two actually), but it turned out that both have a problem when they are adapted to add additional information:

data = [ { continent: 'africa', country: 'gabon', values: [1, 2] }, { continent: 'africa', country: 'chad', values: [3, 4] }, { continent: 'asia', country: 'china', values: [1, 2] } ]; sum_by = 'continent'; rollupAgg = function(data, sum_by) { return d3.nest().key(function(d) { return d[sum_by]; }).rollup(function(group) { return group.reduce(function(prev, cur, index, arr) { return { values: prev.values.map(function(d, i) { return d + cur.values[i]; }), sum_by: sum_by // additional information }; }); }).entries(data); }; 

reduce () does not start if there is only one line in this group, so this returns the following:

 [ { "key": "africa", "values": { "values": [4, 6], "sum_by": "continent" } }, { "key": "asia", "values": { "continent": "asia", "country": "china", // country information shouldn't have been retained "values": [1, 2] } // sum_by information should have been added } ]; 

Can you see a way to change this function so that it returns the desired result?

0
source share
1 answer

It still did not occur to me that a single elementary array would not perform a function; but this makes sense because you are using with one parameter:

 [].reduce(function(prev, curr, i, arr) {});// <-- function is the only param 

When used with one parameter, the behavior is that at the first start of the function i is 1 (not 0), and prev and curr are the first and second elements of the array. Since you have only one element, there is no way to call it in this form.

If you use shortening with the second parameter:

 [].reduce(function(prev, curr, i, arr) {}, { foo:'bar' });// <-- 2nd param {foo:bar} 

it really calls the function, with the first call passing i equal to 0 and prev equal to { foo:'bar' } .

So, I have 2 options:

  • Or change it to pass the 2nd parameter, which in your case should be { values:[0,0] } (and this indicates that values always 2 elements, which will cause a problem if it is larger).

  • Check if group.length == 1 and if so, return group instead of calling reduce.

+1
source

Source: https://habr.com/ru/post/1446005/


All Articles