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...
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
keyor 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;});
const playersByExperience = Object.groupBy(players, (player) => {// instead of creating groups based on a property// we can also return a generated group keyreturn player.yearsActive <= 2 ? 'Rookies' : 'Veterans';});
const playersByTeam = players.reduce((group, player) => {if (group.hasOwnProperty(player.team)) {group[player.team] = [...group[player.team], player];return group;}group[player.team] = [player];return group;},{} as Record<string, Player[]>,);
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!