javascript - Group by java-script Array object -
i have below array object in javascript
[ ["english", 52], ["hindi", 154], ["hindi", 241], ["spanish", 10], ["french", 65], ["german", 98], ["russian", 10] ]
what best way group array item based on language , average values in java-script.
i using below code grouping.
function (scores) { var map = {}; (var = 0; < scores.length; i++) { var score = map[scores[i][0]]; if (score) { score = { 'sum': score.sum + scores[i][1], 'count': score.match + 1, 'language': scores[i][0] }; score.avg = math.round(score.sum / score.count); map[scores[i][0]] = score; } else { map[scores[i][0]] = { 'sum': scores[i][1], 'count': 1, 'language': scores[i][0], 'avg': scores[i][1] }; } } return map; }
var data = [["english", 52], ["hindi", 154], ["hindi", 241], ["spanish", 10], ["french", 65], ["german", 98], ["russian", 10]]; var aggregate = data.reduce(function(prev,curr){ var key = curr[0]; if(!prev[key]){ prev[key]={lang:key,count:0,total:0}; } var dt = prev[key]; dt.count++; dt.total+=curr[1]; dt.avg=dt.total/dt.count; return prev; },{}); console.log(aggregate);
Comments
Post a Comment