Skip to content

How to idomatically reduce an Array into a Map #1608

Answered by mlegenhausen
edalex-ian asked this question in Q&A
Discussion options

You must be logged in to vote

I would recommend to take a look at the groupBy function from ReadonlyNonEmptyArray and adapt it to the use with Map. Then you can simply map over all grouped values and determine the array size of each entry.

You should also think about if you really need a Map cause a look up or modification is more expensive as for example for a Record. If you would consider using a Record your example can be reduced to this:

import { pipe } from 'fp-ts/function'
import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray'
import * as RA from 'fp-ts/ReadonlyArray'
import * as RR from 'fp-ts/ReadonlyRecord'

pipe([1, 2, 3, 2, 3, 2, 4], RNEA.groupBy(String), RR.map(RA.size)) // { '1': 1, '2': 3, '3': 2, '4': 1 }

T…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@edalex-ian
Comment options

Answer selected by edalex-ian
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants