Skip to content

Instantly share code, notes, and snippets.

View fortwo's full-sized avatar

Francesco Fortunati fortwo

View GitHub Profile
@fortwo
fortwo / groupByMultipleKeys.js
Last active November 26, 2020 21:10
Based on the very well written https://gist.github.com/robmathers/1830ce09695f759bf2c4df15c29dd22d, this is a groupBy method that supports multiple keys.
const groupBy = (data, keys) => { // `data` is an array of objects, `keys` is the array of keys (or property accessor) to group by
// reduce runs this anonymous function on each element of `data` (the `item` parameter,
// returning the `storage` parameter at the end
return data.reduce((storage, item) => {
// returns an object containing keys and values of each item
const groupValues = keys.reduce((values, key) => {
values[key] = item[key];
return values;
}, {});
@fortwo
fortwo / groupBy.js
Created June 22, 2020 12:45
A more readable and annotated version of the Javascript groupBy from Ceasar Bautista (https://stackoverflow.com/a/34890276/1376063)
const groupBy = (data, keys) => { // `data` is an array of objects, `keys` is the array of keys (or property accessor) to group by
// reduce runs this anonymous function on each element of `data` (the `item` parameter,
// returning the `storage` parameter at the end
return data.reduce((storage, item) => {
//
const groupValues = keys.reduce((values, key) => {
values[key] = item[key];
return values;
}, {});