DEV Community

Cover image for GroupBy in JavaScript: the easy way to index and organize data
Angela Caldas
Angela Caldas

Posted on

GroupBy in JavaScript: the easy way to index and organize data

Ler em PT-BR

How many times have you needed to use reduce to organize arrays of objects? In my previous article on Data indexing for front-end applications, I explored how to organize complex structures using reduce and Map.

But let’s be honest: reduce tends to make code complex and hard to understand...

Want some good news? Since the release of ECMAScript 2024, we have a much simpler, more expressive, and more readable way to do this using the Object.groupBy and Map.groupBy methods.

Table of Contents

Why group data?
Object.groupBy
Map.groupBy
Conclusion

Group hug!


Why group data?

Grouping data is a form of indexing: you take a linear list and reorganize everything using a key. This type of organization improves performance, while also making searches and data consumption in dynamic interfaces easier.

Before these new APIs, using reduce was almost mandatory. It worked, of course, but it required writing more code than necessary, and readability ended up suffering:

// How we used to do it before
const products = [
  { name: "iPhone", category: "electronics", price: 5000 },
  { name: "Laptop", category: "electronics", price: 3000 },
  { name: "T-shirt", category: "clothing", price: 50 },
  { name: "Pants", category: "clothing", price: 120 },
];

const grouped = products.reduce((acc, product) => {
  const category = product.category;
  if (!acc[category]) acc[category] = [];
  acc[category].push(product);
  return acc;
}, {});
Enter fullscreen mode Exit fullscreen mode

Object.groupBy

Object.groupBy solves the simplest grouping case — the one where the key is a string. You pass the list and a function that returns the key, and that’s it. JavaScript returns an organized object, without requiring manual initialization, checks, or boilerplate.

const productsByCategory = Object.groupBy(
  products, // the list goes here
  (product) => product.category // and the function goes here
);

console.log(productsByCategory);
console.log(productsByCategory instanceof Object); // true
Enter fullscreen mode Exit fullscreen mode

The result is direct, clean, and easy to interpret:

{
  electronics: [
    { name: 'iPhone', category: 'electronics', price: 5000 },
    { name: 'Laptop', category: 'electronics', price: 3000 }
  ],
  clothing: [
    { name: 'T-shirt', category: 'clothing', price: 50 },
    { name: 'Pants', category: 'clothing', price: 120 }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Back to table of contents


Map.groupBy

Map.groupBy, on the other hand, handles cases where the key cannot be treated as plain text. When you need to group by:

  • dates,
  • objects,
  • symbols,
  • or any value that should not become a string,

this is where it makes a difference:

class Professor {    
  constructor(name, specialty) {
    this.name = name;
      this.specialty = specialty;
  }
}

const professor1 = new Professor("John", "Mathematics");
const professor2 = new Professor("Mary", "Physics");

const students = [
  { name: "Carlos",  age: 20, professor: professor1 },
  { name: "Beatriz", age: 22, professor: professor2 },
  { name: "Peter",   age: 19, professor: professor1 }
];

const studentsByProfessor = Map.groupBy(students, student => student.professor);
console.log(studentsByProfessor);

/*
Map(2) {
  Professor { name: 'John', specialty: 'Mathematics' } => [
    { name: 'Carlos', age: 20, professor: [Professor] },
    { name: 'Peter', age: 19, professor: [Professor] }
  ],
  Professor { name: 'Mary', specialty: 'Physics' } => [
    { name: 'Beatriz', age: 22, professor: [Professor] }
  ],
}
*/
Enter fullscreen mode Exit fullscreen mode

Accessing or manipulating groups becomes more explicit, which helps a lot in larger projects:

console.log(studentsByProfessor.get(professor1));

/*
[
  {
    name: 'Carlos',
    age: 20,
    professor: Professor { name: 'John', specialty: 'Mathematics' }
  },
  {
    name: 'Peter',
    age: 19,
    professor: Professor { name: 'John', specialty: 'Mathematics' }
  }
]
*/
Enter fullscreen mode Exit fullscreen mode

The main advantage is exactly this: Map preserves the original type of the key, which avoids automatic conversions and ambiguities — something that can cause silent issues when using regular objects.

In the end, Map.groupBy becomes the more flexible alternative for anyone dealing with diverse collections in modern JavaScript.

Thanks to @matheusgondra for the example above.

Back to table of contents


Conclusion

The new grouping methods simplify something that has always been part of our development routine. Instead of writing repetitive blocks with reduce, we can now rely on native solutions designed exactly for this purpose.

When combined with the techniques I presented in the previous article, they make the indexing flow clearer, more direct, and much more expressive.

If you work with lists, filters, tables, or dashboards, these APIs are worth trying. They will probably make your code much leaner.


⚠️ Compatibility note

If you are wondering about browser support, good news: according to data from Can I Use, both Object.groupBy and Map.groupBy are widely supported in modern browsers.
The only relevant exception is Internet Explorer, which does not support these APIs — and will not receive support.

In other words: if your audience does not use IE, you can adopt groupBy without concerns.

Top comments (0)