Last active
June 10, 2019 11:36
-
-
Save Slackwise/43d4b4a6c315e4c2eb30fd60e347aa26 to your computer and use it in GitHub Desktop.
Vanilla ES6 functions to group database result sets, and example usage.
This file contains 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
returnedUsers = { | |
"users": [ | |
{ | |
"name": "dusan", | |
"id": 1, | |
"skill": "node.js", | |
"skill_id": 1 | |
}, | |
{ | |
"name": "dusan", | |
"id": 1, | |
"skill": "php", | |
"skill_id": 2 | |
}, | |
{ | |
"name": "dusan", | |
"id": 1, | |
"skill": "mongodb", | |
"skill_id": 3 | |
}, | |
{ | |
"name": "jaca", | |
"id": 2, | |
"skill": "angular", | |
"skill_id": 4 | |
}, | |
{ | |
"name": "jaca", | |
"id": 2, | |
"skill": "reactjs", | |
"skill_id": 5 | |
}, | |
] | |
}; | |
const groupBy = (array, key) => | |
array.reduce((a, c) => ( | |
{ | |
...a, | |
[c[key]]: [...a[c[key]] || [], c] | |
} | |
), {}); | |
const uniques = (...values) => | |
Array.from(new Set([].concat(...values).filter(Boolean))); | |
const singularize = array => | |
array.length == 1 ? array[0] : array; | |
const singularizedUniques = (...values) => | |
singularize(uniques(...values)); | |
const mergeCollect = array => | |
array.reduce((mergedObject, curentObject) => | |
Object.entries(curentObject).reduce((newObject, [k, v]) => ( | |
{ | |
...newObject, | |
[k]: singularizedUniques(newObject[k], v) | |
} | |
), mergedObject) | |
, {}); | |
const groupByKey = (array, key) => | |
Object.fromEntries(Object.entries(groupBy(array, key)).map(([k, v]) => [k, mergeCollect(v)])); | |
groupByKey(returnedUsers.users, 'id'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment