Skip to content

group

Sort an array of items into groups

114 bytes

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. Generally, this can be useful to categorize an array.

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 _
_
.
group<{
name: string;
source: string;
}, string>(array: readonly {
name: string;
source: string;
}[], getGroupId: (item: {
name: string;
source: string;
}) => string): {
[x: string]: {
name: string;
source: string;
}[] | undefined;
}
export group

Sorts an array of items into groups. The return value is a map where the keys are the group IDs the given getGroupId function produced and the value is an array of each item in that group.

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

@example

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

@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] }