2

大批:

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

理想输出:

2, 3, 5, 9, 4

PHP 使用 and 使这变得简单array_count_values()arsort()但 javascript 被证明有点困难。有什么帮助吗?


另外,返回包含计数的内容怎么样?为将来的需要

4

1 回答 1

4

计算唯一条目,创建唯一数组,然后根据计数排序

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]

您的示例同时具有 one9和 one 4,因此如果要定义订单,则需要进行更多工作。否则;

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}
] */

现在,要获得index的i,您需要这样做result[i].value,并且它是 weighting result[i].weight

于 2013-08-02T01:25:41.230 回答