groupBy

collection

Creates an object composed of keys generated from the results of running each element of collection through iteratee. The order of grouped values is determined by the order they occur in collection.

Signature

groupBy<T>(collection: T[], iteratee: ((value: T) => PropertyKey) | keyof T): Record<PropertyKey, T[]>

Parameters

NameTypeDescription
collectionT[]The collection to iterate over
iteratee((value: T) => PropertyKey) | keyof TThe iteratee to transform keys (can be a function or property name)

Returns

Record<PropertyKey, T[]> - Returns the composed aggregate object

Examples

Group by function result

import { groupBy } from 'dashlite'

const result = groupBy([6.1, 4.2, 6.3], Math.floor)
console.log(result)

Output:

{ '4': [4.2], '6': [6.1, 6.3] }

Group by property

import { groupBy } from 'dashlite'

const users = [
  { name: 'Alice', role: 'admin' },
  { name: 'Bob', role: 'user' },
  { name: 'Charlie', role: 'admin' }
]
const result = groupBy(users, 'role')
console.log(result)

Output:

{ admin: [{...}, {...}], user: [{...}] }

Available since version 1.2.0