Appearance
groupBy
Groups items by the key a function returns for each of them.
Usage
ts
import { groupBy } from 'tsu'
const animals = [
{ name: 'Kermit', type: 'frog' },
{ name: 'Mr. Toad', type: 'toad' },
{ name: 'Slippy Toad', type: 'toad' }
]
groupBy(animals, (animal) => animal.type)
// [
// ['frog', [{ name: 'Kermit', type: 'frog' }]],
// ['toad', [{ name: 'Mr. Toad', type: 'toad' }, { name: 'Slippy Toad', type: 'toad' }]]
// ]
groupBy([3, 2, 4, 1, 6], (n) => n % 2 === 0)
// [[false, [3, 1]], [true, [2, 4, 6]]]Type Definitions
ts
/**
* @param array - The array.
* @param by - The function returning the key to group an item under.
* @returns The tuple of each key and its items, in the order the keys were first seen.
*/
function groupBy<T, K>(array: readonly T[], by: (item: T) => K): [K, T[]][]