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 will be the be
Solution 1:
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);
Solution 2:
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
Solution 3:
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);
Solution 4:
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);
Solution 5:
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);
Post a Comment for "Group By Java-script Array Object"