数组:
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更加难以理解。有什么帮助吗?
另外,如果还要包含计数呢?为了将来的需要
答案 0 :(得分:3)
计算唯一条目,创建唯一数组,然后根据计数进行排序
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
,因此如果您希望定义订单,则需要做更多工作。否则;
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
获取值,您需要result[i].value
,并且权重为result[i].weight
。