0

I have an array with some duplicates value. I have removed all duplicates value and get his count(repeat). Now I have to sort this data according to his count.

Example:

let duplicatis_data = ['a','a','b','b','b','c','c','c','c','d','e'];

Expected output

    c->4
    b->3
    a->2
    d->1
    e->1

There is lots of example with removing the duplicates and return the count but they did not make filter according to count. So this is not a duplicate of those questions like below.

How to count duplicate value in an array in javascript

6
  • Does this answer your question? Javascript: sort elements in array by their frequencies Commented Oct 10, 2020 at 19:24
  • Group them, turn the object into an array (Object.entries()) and sort that entry -> done Commented Oct 10, 2020 at 19:27
  • @RahulBhobe I want the count for that frequency as well as I mention the expected output. Commented Oct 11, 2020 at 7:35
  • @Andreas Can you please share a example? Commented Oct 11, 2020 at 7:35
  • @Mannusaraswat - See posted answer. Commented Oct 11, 2020 at 7:46

1 Answer 1

1

Calculate the frequency and then sort the array based on the frequency:

let duplicatis_data = ['a','a','b','b','b','c','c','c','c','d','e'];

   
const freq = duplicatis_data.reduce((c, v) => (c[v] = (c[v] || 0) + 1, c), {});

const result = Object.entries(freq).sort((x, y) => y[1] - x[1]);

console.log(JSON.stringify(result));

Sign up to request clarification or add additional context in comments.

3 Comments

I already get that result but my question is how can I sort that data? like{ "c": 4, "b": 3, "a": 2, "d": 1, "e": 1 }
The new result is an array, and not an object. There is no notion of an "order" in an object.
That's fine. Thanks, you save my day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.