Skip to content

counting

Creates an object with counts of occurrences of items

122 bytes
since v12.1.0

Usage

Given an array of objects and an identity callback function to determine how each object should be identified. Returns an object where the keys are the id values the callback returned and each value is an integer telling how many times that id occurred.

import * as
import _
_
from 'radashi'
const
const gods: {
name: string;
culture: string;
}[]
gods
= [
{
name: string
name
: 'Ra',
culture: string
culture
: 'egypt',
},
{
name: string
name
: 'Zeus',
culture: string
culture
: 'greek',
},
{
name: string
name
: 'Loki',
culture: string
culture
: 'greek',
},
]
const
const countingByCulture: Partial<Record<string, number>>
countingByCulture
=
import _
_
.
function counting<{
name: string;
culture: string;
}, string>(array: readonly {
name: string;
culture: string;
}[], identity: (item: {
name: string;
culture: string;
}) => string): Partial<Record<string, number>>

Counts the occurrences of each unique value returned by the identity function when applied to each item in the array.

If no occurrences are found, the key will not be present in the returned object.

@see ― https://radashi.js.org/reference/array/counting

@example

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

@version ― 12.1.0

counting
(
const gods: {
name: string;
culture: string;
}[]
gods
,
g: {
name: string;
culture: string;
}
g
=>
g: {
name: string;
culture: string;
}
g
.
culture: string
culture
) // => { egypt: 1, greek: 2 }