0

I have below array object in JavaScript

  [ ["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10] ]

What will be the best way to group by array item based on language and their average values in java-script.

I am using below code to do grouping.

function (Scores) {
            var map = {};
            for (var i = 0; i < 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;
        }
1
  • Desired output? What have you tried? Commented May 28, 2016 at 13:32

5 Answers 5

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

The generalize method:

var groupList =   [ ["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10] ]
function groupByProperty (groupList, groupIndex) {
    var groupBy = {};
    groupList.forEach(function(group){
        if(groupBy[group[groupIndex]]){
            groupBy[group[groupIndex]].push(group);
        }
        else {
            groupBy[group[groupIndex]] = [];
            groupBy[group[groupIndex]].push(group)
        }
    })
    for(key in groupBy){
        if (groupBy.hasOwnProperty(key)) {
            console.log(key + ',' + JSON.stringify(groupBy[key]))
        }
    }
}
groupByProperty(groupList,0)//For state
groupByProperty(groupList,1)//For average

Comments

0

A proposal with the same style as the input array.

var data = [["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10]],
    result = [];

data.forEach(function (a) {
    if (!this[a[0]]) {
        this[a[0]] = { data: [], result: [a[0], 0] };
        result.push(this[a[0]].result);
    }
    this[a[0]].data.push(a[1]);
    this[a[0]].result[1] = this[a[0]].data.reduce(function (a, b) { return a + b; }) / this[a[0]].data.length;
}, Object.create(null));

console.log(result);

Comments

0

Try this code..

var items = [ ["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10] ];
for(var i=0;i<items.length;i++)
{
  var sum=items[i][1],cnt=1,avg=0;
  for(var j=i+1;j<items.length;j++)
  {    
    if(items[i][0] == items[j][0]){
      sum+=items[j][1];
      cnt++;
      items.splice(j, 1);
    } 
  }
  avg = sum/cnt;
  items[i][1] = avg;
}

console.log(items);

Comments

0

Well OK.. for a change lets do this O(n) with a single reduce.

var data = [ ["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10] ],
    avrg = (a) => a.reduce((p,c) => p+c)/a.length,
 reduced = data.reduce((p,c,i,a) => ((a[c[0]]) ? (a[c[0]].v.push(c[1]),
                                                  p[a[c[0]].j][1] = avrg(a[c[0]].v))
                                               : (a[c[0]] = {"v":[c[1]], "j":p.length},
                                                  p.push([c[0],c[1]])),
                                     p),[]);
console.log(reduced);

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.