简体   繁体   中英

How to sort a javaScript array according to his duplication count

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

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM