Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Group Data with JavaScript `Map.groupBy()`

1 min read .
Group Data with JavaScript `Map.groupBy()`

Map.groupBy() groups iterable values into a Map. The callback determines the key for each group, and every map value is an array of matching elements.

Basic Example

const numbers = [1, 2, 3, 4, 5, 6];

const grouped = Map.groupBy(numbers, (number) =>
  number % 2 === 0 ? 'even' : 'odd'
);

console.log(grouped.get('even')); // [2, 4, 6]

Group Objects

const products = [
  { name: 'Laptop', category: 'Electronics' },
  { name: 'Shirt', category: 'Clothing' },
  { name: 'Phone', category: 'Electronics' },
];

const grouped = Map.groupBy(products, (product) => product.category);

Arbitrary Map Keys

The main advantage over Object.groupBy() is that map keys can be objects and other values without being converted to property keys:

const active = { label: 'active' };
const inactive = { label: 'inactive' };

const users = [
  { name: 'Alice', enabled: true },
  { name: 'Bob', enabled: false },
];

const grouped = Map.groupBy(users, (user) =>
  user.enabled ? active : inactive
);

Map.groupBy() vs. Object.groupBy()

Use Object.groupBy() when string or symbol property keys are a natural result. Use Map.groupBy() when you need arbitrary key values or prefer the Map API.

Both preserve the original order of values inside each group and leave the source collection unchanged.

Compatibility

These grouping APIs are relatively new. Verify support in the runtimes you target or provide a compatible fallback when necessary.

Conclusion

Map.groupBy() provides a direct alternative to custom grouping loops and reduce code. It is particularly useful when group keys are not naturally strings or symbols.

Related Posts

chevron-up