按频率排序数组 [英] Sort array by frequency

查看:122
本文介绍了按频率排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算数组中每个字符串的次数,并按它们在数组中存在的次数进行排序

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

我现在有这个代码

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.

例如,它输出

apple - 1
banana - 5
cherry - 4

但我需要这个

banana - 5
cherry - 4
apple - 1

提前感谢

推荐答案

两个经过。首先,计算每个单词的出现次数:

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

counter = {}
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];
});

这篇关于按频率排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆