Sort array by frequency

我的未来我决定 提交于 2021-02-17 02:51:05

问题


I would like to count how many times is every string in array and sort them by number of times they exist in array

I have this code now

hlasy.sort();

var zaciatok = null;
var pocet = 0;
for (var i = 0; i < hlasy.length; i++) {
    if (hlasy[i] != zaciatok) {
        if (pocet > 0) {
            console.log(zaciatok + ' má ' + pocet + ' hlasov');
        }
        zaciatok = hlasy[i];
        pocet = 1;
    } else {
        pocet++;
    }
}
if (pocet > 0) {
    console.log(zaciatok + ' má ' + pocet + ' Hlasov');
}

it works, but it outputs strings from array sorted by alphabet and no by how many times they are in array.

for example, it outputs

apple - 1
banana - 5
cherry - 4

but I need this

banana - 5
cherry - 4
apple - 1

thanks in advance


回答1:


Two passes. First, compute the number of occurrences of each word:

counter = Object.create(null);
words.forEach(function(word) {
   counter[word] = (counter[word] || 0) + 1;
});

Then, sort the array by comparing two words' counts:

words.sort(function(x, y) {
   return counter[y] - counter[x];
});


来源:https://stackoverflow.com/questions/36008637/sort-array-by-frequency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!