Skip to content

Instantly share code, notes, and snippets.

@nash403
Created October 10, 2016 14:23
Show Gist options
  • Save nash403/16cf19a75fd147db833a3a698ccd87bc to your computer and use it in GitHub Desktop.
Save nash403/16cf19a75fd147db833a3a698ccd87bc to your computer and use it in GitHub Desktop.
Group array elements upon a criteria.
/*
* @param property string, number or function. This is the crieteria of the grouping function
*/
function groupBy(arr, property) {
return arr.reduce( (memo, el, i) => {
let grpProperty = (() => {
if (typeof property === 'string' || typeof property === 'number') {
return el[property];
} else if (typeof property === 'function') {
return property(el, i, arr);
}
})();
if (!grpProperty) return memo;
if (!memo[grpProperty]) { memo[grpProperty] = []; }
memo[grpProperty].push(el);
return memo;
}, {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment