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

Rahul Bhobe
  • 4,165
  • 4
  • 17
  • 32
Mannu saraswat
  • 1,061
  • 8
  • 15

1 Answers1

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));
Rahul Bhobe
  • 4,165
  • 4
  • 17
  • 32