Jean Dupont Jean Dupont - 3 months ago 11
Javascript Question

Javascript calculate average after groupement

I'm working with crossfilter and dc.js in order to make a dashboard.

What I have ?

Let's consider these documents :

{
"Mkt_Al": "AZA",
"Orig" : "PTH",
"Dest" : "GMP",
"Qsi" : 2

}

{
"Mkt_Al": "AZA", // here the same triplet
"Orig" : "PTH",
"Dest" : "GMP",
"Qsi" : 3

}

{
"Mkt_Al": "AZA", // here the same triplet
"Orig" : "PTH",
"Dest" : "GMP",
"Qsi" : 4

}


What I want ?

I should group documents by the triplet (
Mkt_Al
,
Orig
,
Dest
) then I should calculate the average of the
Qsi
in this group.

{
"Mkt_Al" : "AZA",
"Orig" : "PTH",
"Dest" : "GMP",
"Qsi" : 2,
"Avg_Qsi" : 3


}

{
"Mkt_Al" : "AZA", // here the same triplet
"Orig" : "PTH",
"Dest" : "GMP",
"Qsi" : 3,
"Avg_Qsi" : 3
}

{
"Mkt_Al" : "AZA", // here the same triplet
"Orig" : "PTH",
"Dest" : "GMP",
"Qsi" : 4,
"Avg_Qsi" : 3

}


How to do that ?

I have a
dataSet
, and with dc.js
datatable
I tried to draw a data table with a column which will countain this average:

{
label: 'Average Qsi in this route',
format: function (d)
{
var total=0,avg=d.Qsi;
for (var i = 0; i < dataSet.length; i++)
{
if (dataSet[i].Mkt_Al == d.Mkt_Al
&& dataSet[i].Orig == d.Orig
&& dataSet[i].Dest == d.Dest)
{ total = total+1; avg=(avg+dataSet[i].Qsi/total); }

}
return avg;
}
}


Please how can I achieve the above ?

Answer

I was very near from the result :

 {
                label: 'Average Qsi in this route', 
                format: function (d) 
   {
                var total=0,qsi=0; // our counters
                for (var i = 0; i < dataSet.length; i++) 
      {
  if (dataSet[i].Mkt_Al == d.Mkt_Al
   && dataSet[i].Orig == d.Orig  
   && dataSet[i].Dest == d.Dest)
  { total++ ; qsi =dataSet[i].Qsi+qsi; } // here total calculate the number of flights with these condition and qsi calculate the sum of documents's qsi which verify these results

       }

                   return (qsi/total).toFixed(3); 
    }
 }