Skip to content

Instantly share code, notes, and snippets.

@varijkapil13
Created April 7, 2019 15:44
Show Gist options
  • Save varijkapil13/26509383bb55dc4778395bbb2d1a7096 to your computer and use it in GitHub Desktop.
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
/**
* 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