I am online
← Back to Articles

New Way to Use the Group By Operation in JavaScript

JavaScriptJuly 2, 2024

There is a new way to use the group by operation in JavaScript! It's very easy.

In the past, grouping array elements by a property was typically done using the Array.reduce method with questionable syntax. Recently, support has been added for the Object.groupBy method, which makes grouping elements really easy.

The first argument is the array, and the second is the callback function that returns the keys in the grouped object.

const products = [
  { name: "T-shirt", category: "clothes", price: 50 },
  { name: "Apple", category: "food", price: 5 },
  { name: "Shoes", category: "clothes", price: 35 },
  { name: "Orange", category: "food", price: 7.5 },
  { name: "Blueberry", category: "food", price: 4.5 },
];

const groupedByCategory = Object.groupBy(products, (p) => p.category);

/* groupedByCategory:
{
  clothes: [
    { name: 'T-shirt', category: 'clothes', price: 50 },
    { name: 'Shoes', category: 'clothes', price: 35 }
  ],
  food: [
    { name: 'Apple', category: 'food', price: 5 },
    { name: 'Orange', category: 'food', price: 7.5 },
    { name: 'Blueberry', category: 'food', price: 4.5 }
  ]
}
*/

(Share with others if you found this useful)

Thanks for reading!