问题
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