Skip to main content
2 of 2
sure it is in JS ... + fixed minor grammatical stuff
Billal Begueradj
  • 3.4k
  • 10
  • 25
  • 34

You can utilize a temporary object for counting and returns an array of objects with date and percentage.

var data = [{
        "date": "1-1-2013",
        "answer": "yes"
    }, {
        "date": "1-1-2013",
        "answer": "no"
    }, {
        "date": "2-1-2013",
        "answer": "no"
    }, {
        "date": "2-1-2013",
        "answer": "no"
    }, {
        "date": "2-1-2013",
        "answer": " "       //this is not answered!
    }, , {
        "date": "2-1-2013",
        "answer": "no"
    }];

function getPercentage(data) {
    var obj = {};
    data.forEach(function (a) {
        if (~['yes','no'].indexOf(a.answer)) {                
            obj[a.date] = obj[a.date] || { yes: 0, no: 0 };
            obj[a.date][a.answer]++;
        }
    });
    return Object.keys(obj).map(function (k) {
        return { 
            date: k,
            percent: obj[k].yes * 100 / (obj[k].yes + obj[k].no)
        };
    });
}
document.write('<pre>' + JSON.stringify(getPercentage(data), 0, 4) + '</pre>');

Nina Scholz
  • 729
  • 4
  • 10