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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -