我有一系列值,我想根据出现的频率排序。现在我设法计算出现的次数,但我无法找出如何对它们进行排序......什么是错的?
<script>
$(document).ready(function() {// graphs and prefixes defined here
var list = new Array();
$.getJSON('data.json', function(data) {
$.each(data.results.bindings, function() {
$.each(this, function(k, v) {
if(!($.trim(v.value) in list)) {
list[$.trim(v.value)] = 0;
}
list[$.trim(v.value)] = list[$.trim(v.value)] + 1;
});
});
list.sort(function(a, b) {
return a.value - b.value;
});
var c = 0;
for (var i in list) {
var html = '<li data-value="'+list[i]+'">'+ (c++) +' '+i+' ( '+list[i]+' )';
$("#list").append(html);
}
});
});
</script>
答案 0 :(得分:2)
function orderByOccurrence(arr) {
var counts = {};
arr.forEach(function(value){
if(!counts[value]) {
counts[value] = 0;
}
counts[value]++;
});
return Object.keys(counts).sort(function(curKey,nextKey) {
return counts[curKey] < counts[nextKey];
});
}
> orderByOccurrence(['a','c','a','c','a','c','c','c','c', 'pllee'])
> ["c", "a", "pllee"]
这将适用于其他基元,包括混合基元,但它们都将转换为字符串。
> orderByOccurrence([1,1,1,1,1, 0, -5, -5, false, false, false])
> ["1", "false", "-5", "0"]