1

I have an array of object of reactions for a certain post.

It looks like this:

reactions: [
    {user: 21, reaction:'haha'},
    {user: 7, reaction:'haha'},
    {user: 15, reaction:'haha'},
    {user: 55, reaction:'wow'},
    {user: 27, reaction:'wow'},
    {user: 87, reaction:'wow'},
    {user: 15, reaction:'heart'},
    {user: 15, reaction:'heart'},
    {user: 95, reaction:'like'},
    {user: 100, reaction:'like'},
    {user: 209, reaction:'like'},
    {user: 122, reaction:'like'},
]

How do I make it so that the result should be : ['like', 'haha', 'wow']

ajunior
  • 23
  • 3
  • are you purposefully omitting heart? have you made any attempt(filter)? – depperm Feb 26 '21 at 15:47
  • Yes, it is ommitted because I only want the first three reactions with the most count. – ajunior Feb 26 '21 at 15:48
  • How many possible reactions are there? – Jordan Schnur Feb 26 '21 at 15:48
  • @JordanSchnur There are 5 reactions – ajunior Feb 26 '21 at 15:49
  • If you have a small amount of reactions you could use a loop and a nested switch statement to count the reactions for each reaction and then compare to find the top 3. – Jordan Schnur Feb 26 '21 at 15:51
  • Does this answer your question? [How to get distinct values from an array of objects in JavaScript?](https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript) – gorak Feb 26 '21 at 15:53
  • I would recommend viewing this question, it is not exactly what you are asking but provides the base answer. https://stackoverflow.com/questions/11792158/optimized-javascript-code-to-find-3-largest-element-and-its-indexes-in-array – Jordan Schnur Feb 26 '21 at 15:53
  • If you had `['haha', 'heart', 'heart', 'haha']` which would have showed up? `haha` or `heart`? – MinusFour Feb 26 '21 at 15:54
  • 1
    Make another object whose keys are the reactions and values are the counts. Then sort the reactions by the counts and take the first 3. – Barmar Feb 26 '21 at 15:54

1 Answers1

3

You could count same reactions with an object, get the entries sort them and get top three for only the keys.

const
    reactions = [{ user: 21, reaction: 'haha' }, { user: 7, reaction: 'haha' }, { user: 15, reaction: 'haha' }, { user: 55, reaction: 'wow' }, { user: 27, reaction: 'wow' }, { user: 87, reaction: 'wow' }, { user: 15, reaction: 'heart' }, { user: 15, reaction: 'heart' }, { user: 15, reaction: 'like' }, { user: 15, reaction: 'like' }, { user: 15, reaction: 'like' }, { user: 15, reaction: 'like' }],
    top3 = Object
        .entries(reactions.reduce((r, { reaction }) => (r[reaction] = (r[reaction] || 0) + 1, r), {}))
        .sort(([, a], [, b]) => b - a)
        .slice(0, 3)
        .map(([k]) => k);

console.log(top3);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392