Created
April 13, 2021 21:48
-
-
Save kjbrum/beb9530a36b75cf8a040c2fd9935f7b8 to your computer and use it in GitHub Desktop.
Group an array of object by a specified key
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
/** | |
* Group an array of object by a specified key | |
* @param {array} items Array of objects | |
* @param {string} key Key to use for grouping | |
* @returns {object} | |
*/ | |
const groupBy = (items, key) => { | |
return items.reduce( | |
(result, item) => ({ | |
...result, | |
[item[key]]: [...(result[item[key]] || []), item], | |
}), | |
{} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment