Group an array of objects by a key

This function groups an array of objects by a certain key.

JavaScript:

let groupBy = (arr, key) => arr.reduce((result, obj) => ({ ...result, [obj[key]]: (result[obj[key]] || []).concat(obj) }), {});

// Example
console.log(groupBy([{ age: 20, name: 'Jack' }, { age: 20, name: 'Jane' }, { age: 21, name: 'John' }], 'age')); // { 20: [{ age: 20, name: 'Jack' }, { age: 20, name: 'Jane' }], 21: [{ age: 21, name: 'John' }] }
console.log(groupBy([{ type: 'apple', color: 'red' }, { type: 'banana', color: 'yellow' }, { type: 'apple', color: 'green' }], 'type')); // { apple: [{ type: 'apple', color: 'red' }, { type: 'apple', color: 'green' }], banana: [{ type: 'banana', color: 'yellow' }] }

TypeScript:

let groupBy = (arr: T[], key: K): { [P in T[K]]?: T[] } => arr.reduce((result, obj) => ({ ...result, [obj[key]]: (result[obj[key]] || []).concat(obj) }), {});

// Example
console.log(groupBy([{ age: 20, name: 'Jack' }, { age: 20, name: 'Jane' }, { age: 21, name: 'John' }], 'age')); // { 20: [{ age: 20, name: 'Jack' }, { age: 20, name: 'Jane' }], 21: [{ age: 21, name: 'John' }] }
console.log(groupBy([{ type: 'apple', color: 'red' }, { type: 'banana', color: 'yellow' }, { type: 'apple', color: 'green' }], 'type')); // { apple: [{ type: 'apple', color: 'red' }, { type: 'apple', color: 'green' }], banana: [{ type: 'banana', color: 'yellow' }] }
Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *