Skip to content

reduce

Reduces a Map to a single value by applying a function to each entry, in insertion order.

Available since v3.0.3

import { reduce } from '@helpers4/map';
// or, from the all-in-one package (same code, one install):
import { reduce } from 'helpers4/map';
reduce<K, V, R>(map: ReadonlyMap<K, V>, fn: function, initial: R): R
ParameterTypeDescription
mapReadonlyMap<K, V>The Map to reduce
fnfunctionFunction invoked with (accumulator, value, key)
initialRInitial accumulator value

R — The final accumulator value

Reduces a Map of numbers to their total.

reduce(new Map([['a', 1], ['b', 2], ['c', 3]]), (acc, value) => acc + value, 0)
// => 6

Reduce can produce a completely different shape than the map values.

reduce(new Map([['a', 1], ['b', 2]]), (acc: string[], _v, key) => [...acc, key], [])
// => ['a', 'b']

View source on GitHub