Developer bit

Simplify Grouping Arrays in JavaScript with Object.groupBy()

Grouping an array of objects in JavaScript no longer needs to be complex. The new Object.groupBy() static method simplifies this task by allowing you to...

Simplify Grouping Arrays in JavaScript with Object.groupBy()

Grouping an array of objects in JavaScript no longer needs to be complex. The new Object.groupBy() static method simplifies this task by allowing you to group elements based on string values returned by the callback function.

Previously, achieving this required manual grouping (using methods like reduce) or relying on external libraries like Lodash. However, with Object.groupBy(), you can achieve the same result in a more readable and concise manner.

Here are the key points:

  • 💫 Functionality: group elements based on a specified string (object key or custom string).
  • 💁 Browser Compatibility: available in modern browsers.
  • 🛠️ TypeScript Support: included in v5.4-beta.
Input data
type Player = { name: string; team: string; yearsActive: number };
const players: Player[] = [
{
name: 'Player 1.1',
team: 'Team One',
yearsActive: 3,
},
{
name: 'Player 1.2',
team: 'Team One',
yearsActive: 5,
},
{
name: 'Player 2.1',
team: 'Team Two',
yearsActive: 1,
},
{
name: 'Player 3.1',
team: 'Team Three',
yearsActive: 8,
},
{
name: 'Player 3.2',
team: 'Team Three',
yearsActive: 2,
},
];
const playersByTeam = Object.groupBy(players, (player) => {
return player.team;
});

To explore and experiment with Object.groupBy(), check out the following TypeScript playground to see the code in action.

Feel free to update this developer bit on GitHub, thanks in advance!

Enjoying the blog?

Support my work

If you enjoyed this post and found it useful, consider supporting my work. It helps me keep creating and sharing content like this. Thank you!