The type of the elements in the array.
The type of the keys extracted from the elements.
The array to group.
The function to extract the key from each element.
const array = [
{ category: 'fruit', name: 'apple' },
{ category: 'fruit', name: 'banana' },
{ category: 'vegetable', name: 'carrot' }
];
const grouped = groupBy(array, x => x.category);
// grouped will be {
// fruit: [{ category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' }],
// vegetable: [{ category: 'vegetable', name: 'carrot' }]
// }
Groups the elements of an array based on a specified key extractor function.
This function takes an array and a function that extracts a key from each element, and returns an object where the keys are the extracted values and the values are arrays of elements that correspond to each key.