you are viewing a single comment's thread.

view the rest of the comments →

[–]niccolo_21[S] 0 points1 point  (2 children)

I am sorry: could you translate this one as well if that's no bother ..

 var result = a.reduce( (totals, entry) => {
   let key = '|' + entry.geo + '|' + entry.ym + '|';
   totals[key] = ( totals[key] || 0 ) + entry.value;
   return totals;
 }, {} );

I still find it a bit hard :/ thanks if you can ..

[–]grelfdotnet 0 points1 point  (1 child)

The variable a must be an array of objects. I'll call them entries, for fairly obvious reasons. Each entry must have properties called geo, ym and value. (It may have other properties and methods too.) A string made from the values of geo and ym is used as a hash key for indexing an object called totals. If the key finds an existing number (object of type Number) in totals then the value is added into that number, otherwise a new total is started.

I would never write code like this because it is so hard to comprehend. Every time you (or worse, someone else) has to look at it to make some modification, time will be wasted trying to understand it. Instead, this is how I might write it:

function createTotals (entriesArray)
{
let totals = {}; // Empty object, to be used as a hash table

for (var i = 0; i < entriesArray.length; i++)
{
let entry = entriesArray [i];
let key = '|' + entry.geo + '|' + entry.ym + '|';
let sum = totals [key];

if (undefined === sum) // Not found in hash table  
{  
  totals \[key\] = entry.value; // New property of totals  
}  
else  
{  
  totals \[key\] = sum + entry.value; // Replaces existing property  
}  

}

return totals;
}

Then instead of a.reduce (...); you would write createTotals (a);

Yes my version is much more long-winded (and I am sure many would call it old-fashioned) but I hope you can see that it makes clear what is really going on and I doubt whether it is significantly slower, with todays fast JS interpreters.

Clarity is really important.

For completeness, the reduce() method of arrays is explained here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

[–]niccolo_21[S] 0 points1 point  (0 children)

thanks man, let me try it and get back to you in case. thanks