Skip to content
Index

[JavaScript] Group values in an array (e.g. objects by a key)

When you have a list of objects, you may want to group all similar objects together by a key. For example, you may have a list of items with a category key, and you want to group all items by this category, for easy access.

const items = [
{ id: 1, name: 'Alice', category: 'Boss' },
{ id: 2, name: 'Bob', category: 'Superstar' },
{ id: 3, name: 'Charlie', category: 'Superstar' },
];
const groups = Object.groupBy(items, ({ category }) => category);
console.log(groups['Boss']); // [{ id: 1, name: 'Alice', category: 'Boss' }]
console.log(groups['Superstar']); // [{ id: 2, name: 'Bob', category: 'Superstar' }, { id: 3, name: 'Charlie', category: 'Superstar' }]

This works with any type of values in the array, and you can put any logic you want in the function that decides what the group key should be:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const groups = Object.groupBy(numbers, (n) => n % 2 === 0 ? 'even' : 'odd');
console.log(groups['even']); // [2, 4, 6, 8, 10]
console.log(groups['odd']); // [1, 3, 5, 7, 9]