.groupBy()
THE-Spellchecker154 total contributions
Published Dec 26, 2023Updated May 15, 2024
Contribute to Docs
The .groupBy()
method groups items according to the value returned by a callback function. The return value of the .groupBy()
method is a null-prototype object that doesn’t inherit any object methods.
Syntax
Object.groupBy(items, callfunc);
items
: It is an array. They will be grouped according to the result of thecallfunc
.callfunc
: It is a callback function. This function returns a string or a symbol.
Example
In the following example, the code groups users by their subscription year:
const subs = [{ userName: 'Lisa', yearSub: 2022 },{ userName: 'Akim', yearSub: 2020 },{ userName: 'Lola', yearSub: 2020 },];const subsByYear = Object.groupBy(subs, (user) => {return user.yearSub;});
Note: To run this code, it is necessary to add a library like Lodash.
The output of the above code will be:
{'2020': [{ userName: 'Akim', yearSub: 2020 },{ userName: 'Lola', yearSub: 2020 }],'2022': [ { userName: 'Lisa', yearSub: 2022 } ]}
All contributors
- THE-Spellchecker154 total contributions
- CecileZanco1 total contribution
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.