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
typePlayer={name:string;team:string;yearsActive:number};const:Player={:,:,:3,},{:,:,:5,},{:,:,:1,},{:,:,:8,},{:,:,:2,},;
const=.groupBy,(player)=>{return.;};
const=.groupBy,(player)=>{// instead of creating groups based on a property// we can also return a generated group keyreturn.<=2?:;};
const=.reduce(group,player)=>{if.hasOwnProperty.{.=....,;return;}.=;return;},{}asRecord<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!