Created
April 7, 2019 15:44
-
-
Save varijkapil13/26509383bb55dc4778395bbb2d1a7096 to your computer and use it in GitHub Desktop.
Grouping elements of an array of objects using a key from the object
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
/** | |
* Will return an object which contains all the elements from the `items` array grouped according to the `key` field | |
* Eg. items = [{name: "ABC", age:2},{name: "DEF", age:2},{name: "GHI", age:2},{name: "JKL", age:3},{name: "MNO", age:3}] | |
* key = "age" | |
* result = {2: [{name: "ABC", age:2},{name: "DEF", age:2},{name: "GHI", age:2}], 3: [{name: "JKL", age:3},{name: "MNO", age:3}]} | |
* @param {Array} items - array of items that needs to be grouped | |
* @param {String} key - key in the object inside the items array for which the grouping is to be performed | |
* @returns {*} - resulting object with grouped elements | |
*/ | |
const groupBy = (items, key) => | |
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