I have an array:
['Online Learning', 'Online Learning', 'Online Learning', 'Communications', 'Communications', 'Intranet']
I’m using the below to find the frequency/occurrences of each value in this array:
const catsReduced = cats.reduce((acc: any, currentValue: any) => (acc[currentValue] = (acc[currentValue] || 0) + 1, acc), {});
This outputs:
{Online Learning: 3, Communications: 2, Intranet: 1}
How would I edit the above reducer to show just:
[3,2,1]
(as number types).
I’m not sure I can be clearer, but please do say if more is required.
2
Answers
Instead of using an object to store the counts, you can directly push the counts into an array.
1-
iterate over the array usingreduce
and count the ocurrences of each element.2-
extract the values (the counts) from the resulting object usingObject.values()
.3-
the resulting array contains the counts of each unique value in the same order they appear in the original array.Edit:
if typescript is giving you that error try changing your lib compiler option toes2017
or later which can be found probably in yourtsconfig.json
fileAn alternative method to get the frequencies is to use
Object.groupBy
, then get the length of each array. (Note that this shortens the code at the cost of wasting some more memory.)