Object.GroupBy functionality
khizerrehandev
Posted on September 19, 2023
Still Experimental Feature
Following Browsers has supported this feature in Chrome, Edge, Safari 117 version.
Before it was Introduced in browser following implementations were done using:
Using Array.reduce method
function groupBy(array, callback) {
return array.reduce((result, item) => {
const key = callback(item);
if (!result[key]) {
result[key] = [];
}
result[key].push(item);
return result;
}, {});
}
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 25 },
{ name: 'David', age: 30 },
]
// Using Reduce Method
const groupByAge = groupBy(people, ({age})=> age);
Using Object.prototype method
Object.groupBy(people, ({age})=> age);
Benefits:
- Implementation is more Abstracted and provided by browser API's
- Noise reduction from developers POV and reducing adding custom support for this method
Important Notes:
The return value of groupBy is an object that does not inherit from %Object.prototype%.
groupBy calls
callbackfn
once for each element in items withcallbackFn(groupItem, index)
just like normal callback functions e.gmap
,filter
.Make sure browser supports this method and it is not recommended for production env as it still needs to be supported by major KEY players by web browsers
It is still not supported in Firefox, Opera, IE refer always caniuseto see supported versions.
Let me know your thoughts via comments and feedback. 💬
Happy coding and Happy Learning! 🎉
Posted on September 19, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.