Created
May 13, 2019 16:43
-
-
Save alexkhismatulin/091cc28b3a216aac001f9cca69044393 to your computer and use it in GitHub Desktop.
Groups array entries based on given path. Uses getProperty function (https://gist.github.com/alexkhismatulin/0dee70114e597a32bcd59c6acc934d79)
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
const groupBy = (arr, path) => { | |
if (!path || typeof path !== "string") return {} | |
return Object.keys(arr).reduce((accum, key) => { | |
const value = getProperty(arr[key], path) | |
if (accum[value]) return { ...accum, [value]: [...accum[value], arr[key]] } | |
return { ...accum, [value]: [arr[key]] } | |
}, {}) | |
} | |
// example | |
const dataset = [ | |
{ | |
name: "Arsen", | |
passport: { | |
issuedAt: "2019", | |
}, | |
}, | |
{ | |
name: "Alex", | |
passport: { | |
issuedAt: "2016", | |
}, | |
}, | |
{ | |
name: "John", | |
passport: { | |
issuedAt: "2019", | |
}, | |
}, | |
] | |
console.log(groupBy(dataset, "passport.issuedAt")) | |
/* | |
Output: | |
{ | |
2016: [ | |
{ | |
name: "Alex", | |
passport: { | |
issuedAt: "2016", | |
}, | |
}, | |
], | |
2018: [ | |
{ | |
name: "Arsen", | |
passport: { | |
issuedAt: "2019", | |
}, | |
}, | |
{ | |
name: "John", | |
passport: { | |
issuedAt: "2019", | |
}, | |
}, | |
], | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment