Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I remove the text from the output of this reduced array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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"]
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading