.groupBy()
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 } ]}
Contribute to Docs
- 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.
Learn JavaScript on Codecademy
- Career path
Full-Stack Engineer
A full-stack engineer can get a project done from start to finish, back-end to front-end.Includes 51 CoursesWith Professional CertificationBeginner Friendly150 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours