skip to Main Content

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


  1. 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"]
      }
    }
    
    Login or Signup to reply.
  2. An 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.)

    const cats = ['Online Learning', 'Online Learning', 'Online Learning', 'Communications', 'Communications', 'Intranet'];
    const res = Object.values(Object.groupBy(cats, x => x)).map(x => x.length);
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search