Last active
November 19, 2019 22:47
-
-
Save KartaviK/f33120a7db7b095339f3f8eaba126d20 to your computer and use it in GitHub Desktop.
Group your array by multiple keys with comparing customization!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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