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.
>Solution :
Instead of using an object to store the counts, you can directly push the counts into an array.
1- iterate over the array using reduce and count the ocurrences of each element.
2-extract the values (the counts) from the resulting object using Object.values().
3- the resulting array contains the counts of each unique value in the same order they appear in the original array.
const cats = ['Online Learning', 'Online Learning', 'Online Learning', 'Communications', 'Communications', 'Intranet'];
const counts = Object.values(cats.reduce((acc, currentValue) => {
acc[currentValue] = (acc[currentValue] || 0) + 1;
return acc;
}, {}));
console.log(counts);
Edit: if typescript is giving you that error try changing your lib compiler option to es2017 or later which can be found probably in your tsconfig.json file
{
"compilerOptions": {
"target": "es2017",
"lib": ["es2017"]
}
}