How to group array items with Object.groupBy()
By Flavio
Tagged: JavaScript
Group an array by a property with Object.groupBy() instead of a reduce loop. See a realistic expense example and Map.groupBy() for object keys.
Object.groupBy() splits a list of items into named groups.
You pass it an iterable and a callback that returns a group key for each item, and you get back an object with one array per key. It replaces a reduce() pattern you’ve probably written plenty of times with a method that says right away what the code does.
If callbacks, objects, and iterables are still new to you, start with the free JavaScript course before diving in here.
Group expenses by category
Say you have a list of expenses:
const expenses = [
{ name: 'Coffee', category: 'food', amount: 4 },
{ name: 'Bus pass', category: 'transport', amount: 45 },
{ name: 'Lunch', category: 'food', amount: 12 },
{ name: 'Train ticket', category: 'transport', amount: 30 },
]
You can group them by their category property like this:
const byCategory = Object.groupBy(
expenses,
expense => expense.category,
)
That gives you an object with one array per category:
const byCategory = {
food: [
{ name: 'Coffee', category: 'food', amount: 4 },
{ name: 'Lunch', category: 'food', amount: 12 },
],
transport: [
{ name: 'Bus pass', category: 'transport', amount: 45 },
{ name: 'Train ticket', category: 'transport', amount: 30 },
],
}
The callback runs once per item, and whatever it returns becomes the key for the array that gets that item.
The callback also gets the current index as a second argument, in case position matters for your grouping logic:
const groups = Object.groupBy(
expenses,
(expense, index) => index < 2 ? 'first-half' : 'second-half',
)
Most of the time you only need the item, so leave the index out unless position is part of the rule. Unlike array methods like map(), the callback doesn’t receive the original iterable as a third argument.
It works with any iterable
You don’t have to pass an array as the first argument. Object.groupBy() accepts any iterable, like a Set or the output of a generator.
Here’s an example grouping values from a Set:
const temperatures = new Set([12, 18, 24, 31])
const byRange = Object.groupBy(temperatures, temperature => {
if (temperature < 15) return 'cold'
if (temperature < 25) return 'mild'
return 'hot'
})
Even when the input is a Set or another iterable, every group in the returned object is still a plain array.
The old reduce() pattern
Before Object.groupBy() existed, you’d usually write something like this with reduce():
const byCategory = expenses.reduce((groups, expense) => {
const key = expense.category
if (!groups[key]) {
groups[key] = []
}
groups[key].push(expense)
return groups
}, {})
It works, sure, though it forces you to juggle a bunch of steps every single time:
- pick the key
- check if that group already exists
- create the array if it doesn’t
- push the item into it
- return the accumulator
Object.groupBy() takes care of all that setup for you. Save reduce() for when you’re building something other than an object of arrays. If you want a refresher on how reduce() works under the hood, check out JavaScript reduce.
Group by a calculated value
Your group key doesn’t have to be an existing property on each item. You can compute whatever label makes sense inside the callback.
For example, you can split numbers into odd and even buckets:
const numbers = [1, 2, 3, 4, 5, 6]
const groups = Object.groupBy(numbers, number =>
number % 2 === 0 ? 'even' : 'odd'
)
Running that gives you:
const groups = {
odd: [1, 3, 5],
even: [2, 4, 6],
}
The same idea works for grouping dates by year, orders by price tier, or messages by sender. As long as the callback returns a key, Object.groupBy() handles the rest.
Group by more than one condition
You can also combine several fields or conditions into a single group label:
const orders = [
{ id: 1, paid: true, shipped: true },
{ id: 2, paid: true, shipped: false },
{ id: 3, paid: false, shipped: false },
]
const byStatus = Object.groupBy(orders, order => {
if (!order.paid) return 'awaiting-payment'
if (!order.shipped) return 'ready-to-ship'
return 'shipped'
})
The callback is a good spot to name a rule like this, as long as you keep it focused on picking the key and don’t mutate the item while you’re in there.
Keys become property keys
Since Object.groupBy() returns a plain object, normal keys get turned into strings.
For instance, returning a boolean from the callback creates groups named true and false:
const products = [
{ name: 'Keyboard', inStock: true },
{ name: 'Display', inStock: false },
]
const byAvailability = Object.groupBy(
products,
product => product.inStock,
)
You read them back just like any other object property:
console.log(byAvailability.true)
console.log(byAvailability.false)
Symbols work as keys too, while objects don’t stay objects in a plain object’s keys. If you need object identity as your key, reach for Map.groupBy() instead.
The result has a null prototype
Object.groupBy() returns an object with a null prototype.
That means it doesn’t inherit properties like toString or constructor, so a group that happens to be named toString won’t clash with Object.prototype.toString.
Static Object methods work on it as usual:
console.log(Object.keys(byCategory))
// ['food', 'transport']
console.log(Object.values(byCategory))
// [foodExpenses, transportExpenses]
What you can’t do is call inherited methods directly on the result, because they aren’t there:
byCategory.hasOwnProperty('food') // TypeError
Use Object.hasOwn() instead:
Object.hasOwn(byCategory, 'food') // true
And if you’re passing the result to a library that expects a normal object with Object.prototype, copy the groups into one:
const regularObject = { ...byCategory }
Transform grouped items afterward
Object.groupBy() puts the original values into buckets without changing them.
If you only want the expense names in each group, group first and map each array afterward:
const namesByCategory = Object.fromEntries(
Object.entries(byCategory).map(([category, items]) => [
category,
items.map(item => item.name),
]),
)
On the other hand, if you only need totals instead of grouped arrays, going straight to reduce() is cleaner:
const totals = expenses.reduce((result, expense) => {
result[expense.category] ??= 0
result[expense.category] += expense.amount
return result
}, {})
Grouping and aggregating are related, just not the same job, so reach for Object.groupBy() when you want buckets and reduce() when you want a summary.
Missing groups do not get empty arrays
Only keys that the callback returns end up in the result. If no item matches a category, that key won’t exist at all:
const byCategory = Object.groupBy(
expenses,
expense => expense.category,
)
console.log(byCategory.office) // undefined
Whenever a group might be missing, add a fallback when you read it:
const officeExpenses = byCategory.office ?? []
You usually don’t need to pre-fill every possible empty group. Most UIs can loop over the groups that do exist using Object.entries():
for (const [category, items] of Object.entries(byCategory)) {
console.log(category, items.length)
}
If the rest of your code expects a fixed list of keys to always be present, set up that default object yourself either before or after grouping.
Use Map.groupBy() for object keys
Map.groupBy() works the same way, except it returns a Map, which means you can use objects as keys:
const design = { id: 1, name: 'Design' }
const backend = { id: 2, name: 'Backend' }
const people = [
{ name: 'Alice', team: design },
{ name: 'Bob', team: backend },
{ name: 'Carol', team: design },
]
const byTeam = Map.groupBy(people, person => person.team)
You can read a group back using the original object:
console.log(byTeam.get(design))
// Alice and Carol
Because Map compares keys by identity, two separate objects with identical fields count as two different keys:
const first = { id: 1 }
const second = { id: 1 }
console.log(first === second) // false
Use Object.groupBy() for string labels like status, category, or year, and switch to Map.groupBy() when you want objects or other values to stay distinct keys.
Grouped objects are shared
Object.groupBy() builds a new outer object and new group arrays without cloning the items inside them. Here’s what happens when you group an array of objects:
const products = [
{ name: 'Keyboard', category: 'accessories', price: 90 },
{ name: 'Mouse', category: 'accessories', price: 40 },
]
const grouped = Object.groupBy(
products,
product => product.category,
)
Now change an object through one of the groups:
grouped.accessories[0].price = 80
console.log(products[0].price) // 80
Both arrays still point to the same product object, so the change shows up in both places.
If you need separate copies so edits don’t leak across, clone the items before grouping:
const grouped = Object.groupBy(
products.map(product => ({ ...product })),
product => product.category,
)
You only need that extra copy step if you plan to mutate the items later. Leaving unchanged objects shared is completely normal and saves work.
Sort the groups or their contents
Object property order isn’t meant for sorting, so when display order matters, turn the result into entries and sort those:
const sortedGroups = Object.entries(byCategory)
.toSorted(([a], [b]) => a.localeCompare(b))
You can also sort the items inside each group without mutating the group array:
const cheapestFood = byCategory.food.toSorted(
(a, b) => a.amount - b.amount,
)
If you want to see more array methods that return a new copy instead of mutating in place, read the immutable array methods.
Build a grouped view
One of the most common places you’ll use Object.groupBy() is shaping raw data for a UI.
Start with a list of transactions:
const transactions = [
{ id: 1, month: '2026-07', amount: 30 },
{ id: 2, month: '2026-08', amount: 12 },
{ id: 3, month: '2026-07', amount: 45 },
]
Group them by month:
const byMonth = Object.groupBy(
transactions,
transaction => transaction.month,
)
Then turn the groups into entries, sort the months, and build the display fields you need:
const sections = Object.entries(byMonth)
.toSorted(([firstMonth], [secondMonth]) =>
secondMonth.localeCompare(firstMonth)
)
.map(([month, items]) => ({
month,
items,
total: items.reduce((sum, item) => sum + item.amount, 0),
}))
Object.groupBy() splits the transactions into buckets, and the map() step builds the display fields without touching the original objects. Sorting and totals stay in their own methods.
Common mistakes
Returning an object from the Object.groupBy() callback is an easy trap to fall into:
const grouped = Object.groupBy(people, person => person.team)
If person.team is an object, JavaScript converts it to a string key like '[object Object]', which silently merges different teams into the same group. Use Map.groupBy() whenever you want object identity as the key.
Another one is calling inherited methods directly on the result. Because the returned object has a null prototype, those methods aren’t there, so stick to Object.keys(), Object.entries(), and Object.hasOwn().
It’s also easy to reach for Object.groupBy() when all you want are totals. Building arrays only to reduce them right afterward does more work than a single reduce().
And avoid mutating items inside the grouping callback:
const grouped = Object.groupBy(expenses, expense => {
expense.amount = Math.round(expense.amount)
return expense.category
})
That modifies the original objects as a side effect of picking a key. Transform your items before grouping, or map the grouped values afterward.
When to use groupBy()
Reach for Object.groupBy() whenever you want several arrays grouped under keys:
- posts grouped by tag
- orders grouped by status
- transactions grouped by month
- people grouped by team
Stick with reduce() when you’re building totals, averages, nested indexes, or some other custom shape.
My advice is to pick the method that matches what you’re doing. If you’re grouping items, Object.groupBy() reads a lot better than rebuilding the same accumulator every time.
Both Object.groupBy() and Map.groupBy() work in current browsers and modern Node.js releases, though you’ll want to check compatibility if you still support older runtimes.
Want me to talk about your product? You can sponsor this site.
Related posts about js: