Skip to content

group

Categorize elements from an array into distinct groups

133 bytes
since v12.1.0

Usage

Given an array of items, group will build up an object where each key is an array of the items that belong in that group.

import * as
import _
_
from 'radashi'
const
const fish: {
name: string;
source: string;
}[]
fish
= [
{
name: string
name
: 'Marlin',
source: string
source
: 'ocean',
},
{
name: string
name
: 'Bass',
source: string
source
: 'lake',
},
{
name: string
name
: 'Trout',
source: string
source
: 'lake',
},
]
const
const fishBySource: {
[x: string]: {
name: string;
source: string;
}[] | undefined;
}
fishBySource
=
import _
_
.
function group<{
name: string;
source: string;
}, string>(array: readonly {
name: string;
source: string;
}[], getGroupId: (item: {
name: string;
source: string;
}, index: number) => string): {
[x: string]: {
name: string;
source: string;
}[] | undefined;
}

Categorizes elements from an array into distinct groups. The function returns an object where each key is a category identifier determined by the getGroupId function, and each value is an array containing all elements that belong to that category.

@seehttps://radashi.js.org/reference/array/group

@example

group([1, 2, 3, 4], (n) => n % 2 === 0 ? 'even' : 'odd')
// { even: [2, 4], odd: [1, 3] }

@version12.1.0

group
(
const fish: {
name: string;
source: string;
}[]
fish
,
f: {
name: string;
source: string;
}
f
=>
f: {
name: string;
source: string;
}
f
.
source: string
source
) // => { ocean: [marlin], lake: [bass, trout] }