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

Group JavaScript Data with `Object.groupBy()`

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

Object.groupBy() groups iterable values by a key returned from a callback and produces an object whose properties contain arrays of matching items.

Group Numbers

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

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

The result has even and odd arrays.

Group Objects by a Property

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

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

Group by a Derived Range

const values = [1, 5, 10, 15, 20, 25, 30];

const grouped = Object.groupBy(values, (value) => {
  if (value <= 10) return '1-10';
  if (value <= 20) return '11-20';
  return '21-30';
});

Object Keys vs. Map Keys

Object.groupBy() is best when group keys naturally become property keys such as strings or symbols. If you need arbitrary object keys, use Map.groupBy() instead.

Compatibility

Object.groupBy() is a newer JavaScript feature. Check the runtimes you support or transpile/polyfill when targeting older environments.

Conclusion

Object.groupBy() replaces a common reduce pattern with a direct, readable API. Return the desired group key from the callback and JavaScript builds the grouped arrays for you.

Related Posts

chevron-up