DEV Community

khizerrehandev
khizerrehandev

Posted on

Object.GroupBy functionality

Still Experimental Feature

Following Browsers has supported this feature in Chrome, Edge, Safari 117 version.

Image description

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);
Enter fullscreen mode Exit fullscreen mode

Using Object.prototype method

 Object.groupBy(people, ({age})=> age);
Enter fullscreen mode Exit fullscreen mode

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 with callbackFn(groupItem, index) just like normal callback functions e.g map, 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! πŸŽ‰

Top comments (0)