Skip to content

Instantly share code, notes, and snippets.

@malikalichsan
Last active June 18, 2020 06:24
Show Gist options
  • Save malikalichsan/09e4af62bc044fc8eab97ced04edbba1 to your computer and use it in GitHub Desktop.
Save malikalichsan/09e4af62bc044fc8eab97ced04edbba1 to your computer and use it in GitHub Desktop.
Group by key and summary value from Array in Javascript
var instagram = [{
"name": "Instagram",
"icon": "https://example.com/instagram.jpg",
"quota": {
"quota": 10,
"unit": "GB"
}
},
{
"name": "Instagram",
"icon": "https://example.com/instagram.jpg",
"quota": {
"quota": 20,
"unit": "GB"
}
},
{
"name": "Instagram",
"icon": "https://example.com/instagram.jpg",
"quota": {
"quota": 30,
"unit": "GB"
}
},
{
"name": "Instagram",
"icon": "https://example.com/instagram.jpg",
"quota": {
"quota": 6.5,
"unit": "GB"
}
},
{
"name": "Instagram",
"icon": "https://example.com/instagram.jpg",
"quota": {
"quota": 5,
"unit": "GB"
}
},
{
"name": "Instagram",
"icon": "https://example.com/instagram.jpg",
"quota": {
"quota": 6,
"unit": "GB"
}
},
{
"name": "Instagram",
"icon": "https://example.com/instagram.jpg",
"quota": {
"quota": 11,
"unit": "GB"
}
},
]
groupBy = (array, key) => {
// Return the end result
return array.reduce((result, currentValue) => {
// If an array already present for key, push it to the array. Else create an array and push the object
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
// Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
return result;
}, {}); // empty object is the initial value for result object
};
let _groupBy = groupBy(instagram, "name");
let items = Object.keys(_groupBy);
let obj = {
name: items,
attr: _groupBy
};
// console.log(_groupBy);
let apps = [];
let sumQuota = 0;
obj.name.map((value, index) => {
let tempAttr = obj.attr[value];
let tempApps = [];
tempAttr.map((val, key) => {
sumQuota = sumQuota + val.quota.quota;
});
tempApps['name'] = obj.name[index];
tempApps['quota'] = sumQuota;
apps.push(tempApps);
});
console.log(apps);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment