JavaScript

Using GroupBy on an array of objects in JavaScript

Advertisements

Array grouping is a fairly common operation in any project. Until recently, we had to either write our own implementation or use third-party libraries when wanting to GroupBy on an array of objects in JavaScript.

That will soon no longer be needed since a native implementation has been introduced in the form of Array.prototype.groupBy. And it is in stage 3 now!

To start using it today, we can use the polyfill provided by core-js.

Using reduce

The reduce method allows us to achieve group by in JavaScript:

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

If you want to read more about how the reduce functionality works, we previously wrote a post about group by in JavaScript that you can read.

Array.prototype.groupBy

Array.groupBy returns an object where each property has the key as the value returned by the arrow function and value as an array of objects matching the criteria.

const groupedObject = array.groupBy((item, index, array) => {
  // ...
  return groupNameAsString;
});
JavaScript

The callback must return a string which would be the group name (JavaScript objects need to have keys as names or Symbols can be used as well).

Examples

Let us assume we have the following array of objects:

const people = [
   { name: 'Saransh', age: 21 },
   { name: 'Wisdom', age: 20 },
   { name: 'Geek', age: 20 }
];
JavaScript

And we want to group them by their age:

const groupByAge = people.groupBy(person => {
  return person.age;
});

console.log(groupByAge); 

// {
//   '20': [
//     { name: 'Wisdom', age: 20 },
//     { name: 'Geek', age: 20 },
//   ],
//   '21': [
//     { name: 'Saransh', age: 21 },
//   ]
// }
JavaScript

An example of grouping a simple array of numbers into odd and even numbers:

const array = [1, 2, 3, 4, 5];

const oddEvenGroups = array.groupBy((num, index, array) => {
  return num % 2 === 0 ? 'even': 'odd';
});

console.log(oddEvenGroups);

// { odd: [1, 3, 5], even: [2, 4] }
JavaScript

Array.prototype.groupByToMap

There are instances where you want a Map instead of a plain JavaScript object. The major benefit is that the keys are then not forced to be strings. The keys of the Map can be of any data type.

groupByToMap works exactly like the groupBy method, the only difference is that it returns a Map.

const groupByAge = people.groupByToMap(person => {
  return person.age;
});

console.log(groupByAge); 

// Map([
//   [20, [
//     { name: 'Wisdom', age: 20 }, 
//     { name: 'Geek', age: 20 },
//   ]],
//   [21, [
//     { name: 'Saransh', age: 21 }
//   ]
// ])
JavaScript

And that is it!

Note: The TypeScript definitions for these methods have not been written yet. Follow this issue for further updates on it.

That is as simple as it gets in terms of implementation and this should land in ES2022 soon and hopefully, the TypeScript definitions are done soon too.

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
Tags: javascript

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…

1 day ago

Native popover API in HTML

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

1 week 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…

2 weeks ago

Object destructuring in TypeScript

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

4 weeks ago

Improve git clone performance in a CI pipeline

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

1 month 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