Skip to content

Instantly share code, notes, and snippets.

@KartaviK
Last active November 19, 2019 22:47
Show Gist options
  • Save KartaviK/f33120a7db7b095339f3f8eaba126d20 to your computer and use it in GitHub Desktop.
Save KartaviK/f33120a7db7b095339f3f8eaba126d20 to your computer and use it in GitHub Desktop.
Group your array by multiple keys with comparing customization!
/**
* Group your items in array by multiple keys!
*
* @param collection
* @param retrieveFunctions
* @param compareFunctions
* @returns {Array}
*/
function groupify(
collection,
retrieveFunctions = {attribute: value => value},
compareFunctions = {attribute: (groupValue, value) => groupValue === value}
) {
let groups = [];
let keyValues = {};
collection.forEach(item => {
for (let attribute in retrieveFunctions) {
keyValues[attribute] = retrieveFunctions.hasOwnProperty(attribute) ? retrieveFunctions[attribute](item[attribute]) : undefined;
}
let group = groups.find(group => {
for (let key in retrieveFunctions) {
if (!group || !group.keys[key]) {
return false;
}
if (compareFunctions[key] instanceof Function) {
if (!compareFunctions[key](group.keys[key], keyValues[key])) {
return false;
}
} else if (group.keys[key] !== keyValues[key]) {
return false;
}
}
return true;
});
!group ? groups.push({keys: keyValues, items: [item]}) : group.items.push(item);
keyValues = {};
});
return groups;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment