计数数组元素和数量降序排序 [英] Counting array elements and sort descending by count

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

问题描述

数组:

5, 5, 5, 9, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3

理想的输出:

2, 3, 5, 9, 4

PHP使这个容易与 array_count_values​​() arsort(),但JavaScript证明有点艰难。任何帮助吗?

PHP made this easy with array_count_values() and arsort(), but javascript is proving a little tougher. Any help?

此外,什么有关返回它含有的计数呢?对于未来的需求。

Also, what about returning it containing the counts as well? For future needs

推荐答案

计数唯一项,创建的唯一身份的数组,然后进行排序基于计数

Count unique entries, create an array of uniques, then sort based upon counts

function count(arr) { // count occurances
    var o = {}, i;
    for (i = 0; i < arr.length; ++i) {
        if (o[arr[i]]) ++o[arr[i]];
        else o[arr[i]] = 1;
    }
    return o;
}

function weight(arr_in) { // unique sorted by num occurances
    var o = count(arr_in),
        arr = [], i;
    for (i in o) arr.push(+i); // fast unique only
    arr.sort(function (a, b) {
        return o[a] < o[b];
    });
    return arr;
}

weight([1, 3, 3, 5, 5, 5, 2, 2, 2, 2]);
// one 1, two 3s, three 5s, four 2s
// [2, 5, 3, 1]

您的例子有两个有一个 9 和一个 4 ,所以如果你想定义的顺序,更多的工作会是必要的。否则;

You example has both one 9 and one 4, so if you want the order defined, more work would be necessary. Otherwise;

weight([5, 5, 5, 9, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3]);
// [2, 3, 5, 4, 9]


要产生的阵列的的的对象

function weight(arr_in) { // unique sorted by num occurances
    var o = count(arr_in),
        arr = [], i;
    for (i in o) arr.push({value: +i, weight: o[i]}); // fast unique only
    arr.sort(function (a, b) {
        return a.weight < b.weight;
    });
    return arr;
}

var result = weight([5, 5, 5, 9, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3]);
/* [
    {"value": 2, "weight": 5},
    {"value": 3, "weight": 4},
    {"value": 5, "weight": 3},
    {"value": 4, "weight": 1},
    {"value": 9, "weight": 1}
] */

现在,得到的的索引 I ,您结果[I] .value的,并为它的权结果[I]。重量

Now, to get the value at index i, you do result[i].value, and for it's weighting result[i].weight.

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

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