Skip to main content
Piotr Majkutewicz
Back to Blog

Array Grouping: The Power of groupBy Method

The Array groupBy method provides a clean and efficient way to group array elements based on specific criteria. This feature simplifies data organization and reduces the need for manual reduce operations.

Basic Usage

Group array elements using a callback function:

javascript
const inventory = [
  { name: 'apple', type: 'fruit' },
  { name: 'carrot', type: 'vegetable' },
  { name: 'banana', type: 'fruit' },
  { name: 'celery', type: 'vegetable' }
];

const grouped = Object.groupBy(inventory, item => item.type);
console.log(grouped);
/* Output:
{
  fruit: [
    { name: 'apple', type: 'fruit' },
    { name: 'banana', type: 'fruit' }
  ],
  vegetable: [
    { name: 'carrot', type: 'vegetable' },
    { name: 'celery', type: 'vegetable' }
  ]
}
*/

Advanced Grouping Patterns

Multiple Criteria Grouping

javascript
const sales = [
  { product: 'apple', category: 'fruit', price: 1.2 },
  { product: 'banana', category: 'fruit', price: 0.8 },
  { product: 'carrot', category: 'vegetable', price: 1.5 }
];

// Group by category and price range
const groupedSales = Object.groupBy(sales, item => {
  const priceRange = item.price < 1 ? 'cheap' : 'expensive';
  return `${item.category}-${priceRange}`;
});

/* Output:
{
  'fruit-expensive': [{ product: 'apple', ... }],
  'fruit-cheap': [{ product: 'banana', ... }],
  'vegetable-expensive': [{ product: 'carrot', ... }]
}
*/

Numeric Grouping

javascript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const groupedByRange = Object.groupBy(numbers, num => {
  if (num <= 3) return 'low';
  if (num <= 7) return 'medium';
  return 'high';
});

/* Output:
{
  low: [1, 2, 3],
  medium: [4, 5, 6, 7],
  high: [8, 9, 10]
}
*/

Performance Considerations

Time Complexity

The groupBy method has a time complexity of O(n), where n is the array length. It performs better than manual reduce operations due to internal optimizations.

javascript
// Performance comparison
const largeArray = Array.from({ length: 10000000 }, (_, i) => ({
  value: i,
  category: i % 3 === 0 ? 'A' : i % 3 === 1 ? 'B' : 'C'
}));

console.time('groupBy');
const groupedNative = Object.groupBy(largeArray, item => item.category);
console.timeEnd('groupBy') // groupBy: 291.717 ms

console.time('reduce');
const groupedReduce = largeArray.reduce((acc, item) => {
  (acc[item.category] = acc[item.category] || []).push(item);
  return acc;
}, {});
console.timeEnd('reduce') // reduce: 539.214 ms

Memory Usage

groupBy creates a new object and maintains references to the original array elements. For very large datasets, consider memory usage and whether you need deep copies of the grouped elements.

Common Use Cases

  • Data analytics and reporting
  • UI organization (grouping items by category)
  • Data preprocessing for charts and visualizations
  • Filtering and organizing API responses

Best Practices

  • Use meaningful key names in grouping functions
  • Consider data structure before choosing grouping criteria
  • Handle edge cases (null/undefined values)
  • Use TypeScript for better type safety with grouped results
  • Consider implementing memoization for expensive grouping operations