flower
flower

Reputation: 2242

How to calculate the average value in a json data in javascript or underscore?

I know that underscore.js have max() and min() function in Collection Functions, but why does it not have avg() function?

I want to calculate the AvgValue in Math in these three student and the avgvalue which is less than 0 must be excluded. I can do it use for or foreach, but how to use underscore function or other js function like map or grep?

The json data is like this:

{ "Data": [
  { "StudentName": "SA",
    "Math": {"AvgValue": 80, "MaxValue": 99, "MinValue": 60 },
    "English": {"AvgValue": 76, "MaxValue": 80, "MinValue": 55 } },
  { "StudentName": "SB",
    "Math": {"AvgValue": 75, "MaxValue": 88, "MinValue": 34 },
    "English": {"AvgValue":98, "MaxValue": 100, "MinValue": 90 } },
  { "StudentName": "SC",
    "Math": {"AvgValue": -1, "MaxValue": -1, "MinValue": -1 },
    "English": {"AvgValue":-1, "MaxValue": -1, "MinValue": -1 } }
], "Total": 3, "AggregateResults": null, "Errors": null }

Upvotes: 1

Views: 3143

Answers (2)

Chris Martin
Chris Martin

Reputation: 30756

why does it not have avg() function?

A Javascript library author has to weigh utility of a feature against the cost it imposes on the size of the library, particularly if the library has a very general purpose.

The goal of Underscore is stated as:

It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?”

I think average is probably too easy to write and too infrequently needed to fit that description.

function mathAverage() {
    function mathScores() { 
        return data['Data'].map(function (student) {
            return student['Math']['AvgValue']; 
        });
    }
    function add(x, y) { return x + y; }
    function sum(xs) { return _.reduce(xs, add); }
    function average(xs) { return sum(xs) / xs.length;}
    function nonnegative(x) { return x >= 0; }
    return average(mathScores().filter(nonnegative));
}

Upvotes: 3

raphaëλ
raphaëλ

Reputation: 6523

You can get the array you want with the grades like this

var grades = data.Data
        .map( function (s) { return s.Math.AvgValue })
        .filter (function (n) {return n > 0}) 
   //   -> [ 80, 75 ]

Then use underscore or a simple for loop to calculate the average

Upvotes: 0

Related Questions