JavaScript Interview Question #192

How would you group an array of objects by a property?

Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

Grouping converts a flat collection into groups based on a key such as category, status, or department. It can be implemented with reduce and an object or Map, and modern environments may also provide grouping APIs depending on the supported runtime.

Detailed Explanation

Grouping converts a flat collection into groups based on a key such as category, status, or department. It can be implemented with reduce and an object or Map, and modern environments may also provide grouping APIs depending on the supported runtime.

For arbitrary key types, Map is often a strong choice. The implementation should make the desired output shape and key behavior explicit.

Code Example

const products = [
    { name: "A", category: "Phone" },
    { name: "B", category: "Laptop" },
    { name: "C", category: "Phone" }
];

const grouped = products.reduce(
    (result, product) => {
        const key = product.category;
        (result[key] ??= []).push(product);
        return result;
    },
    {}
);

console.log(grouped.Phone);