Group By

Groups the elements of an array based on a provided key-generating function.

CategoryArrays
AuthorPol Gubau
Since1.0.0
Last Updated2025-03-15
TypeSync
CompatibilityUniversal

Example

  • Input

    groupBy([
    	{category: 'fruit', name: 'apple'}, 
    	{category: 'fruit', name: 'banana'}, 
    	{category: 'vegetable', name: 'carrot'}
    ], item => item.category)

    Output:

    {	fruit: [
    		{ category: 'fruit', name: 'apple' }, 
    		{ category: 'fruit', name: 'banana' }], 
    	vegetable: [{category: 'vegetable', name: 'carrot' }]
    }

Return

An object where each key is associated with an array of elements that share that key.

Type: Record<K, T[]>

Props

NameTypeDefaultRequiredDescription
arrT[]nullYesThe array to be grouped.
getKeyFromItem(item: T) => KnullYesA function that generates a key from an element.

Notes

Keys must be a valid property key (string, number, or symbol).

Tags

  • array
  • grouping
  • object

Related