Skip to content

Instantly share code, notes, and snippets.

@kxtxr
Created March 7, 2019 08:54
Show Gist options
  • Save kxtxr/f6511ca1fb324233e7949ee680993587 to your computer and use it in GitHub Desktop.
Save kxtxr/f6511ca1fb324233e7949ee680993587 to your computer and use it in GitHub Desktop.
Method takes a key and groups objects of an array (if running `groupCondition` on the object yields true) by the key passed.
/**
* Method takes a key and groups objects of an array
* (if running `groupCondition` on the object yields true)
* by the key passed.
*
* @param {string} key The key to group the object of the array by
* @param {function} groupCondition Function that is run on every
* object in the array and if it returns true, the object is then grouped
*
* @returns {array} Array of objects grouped by key
*/
Array.prototype.groupBy = function(key, groupCondition) {
if (key === undefined || typeof key !== 'string' || this[0][key] === undefined ) {
throw new Error(`[key ${typeof key}]: Grouping key must be a string and a key in all the objects of the array to be grouped.`);
}
if (groupCondition && typeof groupCondition !== 'function') {
throw new Error(`[groupCondition ${typeof groupCondition}]: Grouping condition must be a function.`);
}
if (!groupCondition) {
groupCondition = () => true;
}
return this.reduce((objectsByKeyValue = [], obj) => {
if (groupCondition(obj)) {
const value = obj[key];
delete obj[key];
objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj);
return objectsByKeyValue;
}
}, {});
}
// USAGE
const groupingCondition = person => person.age >= 30 && person.age <= 40);
const grouped = [
{name: 'Kator', age: 21, gender: 'male' },
{name: 'Sandra', age: 31, gender: 'female' },
{ name: 'John', age: 30, gender: 'male' },
{ name: 'Juliet', age: 39, gender: 'female' }
].groupBy('gender', groupingCondition);
console.log(grouped);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment