1

我有一个值数组,我想根据出现的频率对其进行排序。现在我设法计算出现次数,但我不知道如何对它们进行排序......怎么了?

    <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>
4

1 回答 1

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"]
于 2013-05-24T21:21:30.203 回答