JavaScript

How to groupby using reduce in JavaScript

Advertisements

The groupBy method is one of the reasons people use lodash in their project. In this blog post, we will write our own version of groupBy using reduce and vanilla JavaScript.

What groupBy does?

groupBy works on an array of items, and it groups these items together into an object based on some criterion. Let us assume we have the following blog posts:

let posts = [
  {
    author: 'saransh',
    title: 'Learning context API and the useContext React hook',
  },
  {
    author: 'pranshu',
    title: 'Machine Learning Misconceptions That Software Developers Have',
  },
  {
    author: 'saransh',
    title: 'Understanding the useReducer hook in React',
  },
];
JavaScript

We want our groupBy function to return an object which has all posts written by me (Saransh) and other authors too. That is we want to group posts by author names. Thus:

groupBy(posts, 'author');
JavaScript

will give us the output:

{
  "saransh": [
    {
      "author": "saransh",
      "title": "Learning context API and the useContext React hook"
    },
    {
      "author": "saransh",
      "title": "Understanding the useReducer hook in React"
    }
  ],
  "pranshu": [
    {
      "author": "pranshu",
      "title": "Machine Learning Misconceptions That Software Developers Have"
    }
  ]
}
JavaScript

Now that we understand what groupBy does, let us get to implementing it.

A vanilla JS implementation of groupBy

We will be making use of the array.reduce method for our implementation. The reduce method takes in an array and returns a single value, which is what we want for our groupBy method.

Here is what we already know: We will be taking an input array and a key as an input and returning an object as the output. And we will be using the reduce function to iterate over the input array. Since the output will be an object, we will start with an empty object as our accumulator and then keep adding properties to it as we iterate over the input array. Thus, a skeleton of all this would look like:

const groupBy = (input, key) => {
  return input.reduce((acc, currentValue) => {
    // TODO: implement method
 }, {}); // empty object is the initial value for result object
};
JavaScript

Now, we need to initialize an empty array for each distinct key value if it does not exist. We can do this in two ways:

let groupKey = currentValue[key];
if(!acc[groupKey]) {
  acc[groupKey] = [];
}
JavaScript

And then we need to add the current value to this array and move on to the next iteration of the reduce by returning the object that we just created.

Thus, our groupBy function is completed, and we get our final definition:

const groupBy = (input, key) => {
  return input.reduce((acc, currentValue) => {
    let groupKey = currentValue[key];
    if (!acc[groupKey]) {
      acc[groupKey] = [];
    }
    acc[groupKey].push(currentValue);
    return acc;
  }, {});
};
JavaScript

Note: The latest version has an Array.prototype.groupBy method which can be used to groupby in js. We can use that with a polyfill using core-js if we want to.

And that is all we need to do to implement our own groupBy function. We hope this post helped you learn a bit more about how to use reduce and also create your own groupBy function so that you don’t need to rely on Lodash anymore.

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

Share
Published by
Saransh Kataria

Recent Posts

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

2 weeks ago

Native popover API in HTML

Popovers have been a problem that was typically solved by using a third-party solution. But…

3 weeks ago

Node.js 20.6 adds built-in support for .env files

Node.js 20.6 added built-in support for the .env file. This is an excellent addition to the platform…

4 weeks ago

Object destructuring in TypeScript

Object destructuring is a powerful ES 6 feature that can help developers write cleaner code.…

1 month ago

Improve git clone performance in a CI pipeline

Have you felt particularly annoyed by the time it takes to clone a large repository,…

2 months ago

Fix: Hydration failed because the initial UI does not match what was rendered on the server

Within a React or Next.js app, if you encounter the error "Hydration failed because the…

2 months ago
Advertisements