0

I have a json response where have to calculate the average of "throughput_kbps" where protocol name is "TCP" for each result array.

I using Javascript/Angularjs for this

Please refer This json

Thanx in advance

5
  • filter the results for "TCP", pluck the throughput_kbps of that set, sum the set, divide by the count of the set. Commented Mar 3, 2016 at 6:31
  • Are you using underscorejs? Commented Mar 3, 2016 at 6:32
  • @dandavis Thanx but Any sample example for this ? Commented Mar 3, 2016 at 6:33
  • @DivakarDass no .. Using Angularjs only Commented Mar 3, 2016 at 6:33
  • 2
    fetch("https://raw.githubusercontent.com/openstack/vmtp/master/doc/source/_static/example.json") .then(x=>x.json()).then(x=>x.flows.map(y=>y.results.filter(k=>k.protocol=="TCP"))) .then(r=>r.reduce((a,b)=>a.concat(b))) .then(x=>[x.length,x.map(y=>y.throughput_kbps)]) .then(x=>[x[0], x[1].reduce((a,b)=>+a+ +b)]) .then(r=>r[1]/r[0]) .then(alert) Commented Mar 3, 2016 at 6:42

3 Answers 3

2

You could do something like this:

var len1 = obj['flows'].length;
for (var i=0; i<len1; i++) 
{
   var tmp = obj.['flows'][i];
   var len2 = tmp.['results'].length;
   var mean = 0;
   for (var j=0; j<len2; ++j)
   {
      var tmpResult = tmp.['results'][j];
      if (tmpResult['protocol'] === 'TCP')
         mean += tmpResult['throughput_kbps'];
   }
   console.log(mean);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

var sum = 0;
var count = 0;

data.flows.map(function(d){
    return d.results.filter(function(res){
        if(res.protocol == 'TCP'){
            sum += res.throughput_kbps;
            count++;
            return sum;
        }
    })
});

var avg = sum/count;

Comments

0

Pass your JSON as an argument to this function. This'll return you the average throughput you ask for.

function calculateThroughput(json){
 var flowsObj = json.flows;
 var throughputSum = 0;
 var noOfSamples = 0;

 for(noOfFlows in flowsObj){
    var resultObj = flowsObj[noOfFlows].results;
    for(noOfResults in resultObj){
        if(resultObj[noOfResults].protocol == "TCP"){
            throughputSum += resultObj[noOfResults].throughput_kbps;
            noOfSamples++;
        }
    }
 }
 return (throughputSum/noOfSamples);
};

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.