按频率返回数组和出现的值

时间:2015-01-21 21:20:18

标签: javascript sorting frequency

所以我有这段代码

Array.prototype.byCount= function(){
    var itm, a= [], L= this.length, o= {};
    for(var i= 0; i<L; i++){
        itm= this[i];
        if(!itm) continue;
        if(o[itm]== undefined) o[itm]= 1;
        else ++o[itm];
    }
    for(var p in o) a[a.length]= p;
    return a.sort(function(a, b){
        return o[b]-o[a];
    });
}

source

这几乎是我所需要的,除了它不会返回带有值的出现次数。

我试图重写它,但我总是在排序部分失败。

感谢您的帮助

3 个答案:

答案 0 :(得分:3)

这应该做你想要的:

Array.prototype.byCount= function(){
    var itm, a= [], L= this.length, o= {};
    for(var i= 0; i<L; i++){
        itm= this[i];
        if(!itm) continue;
        if(o[itm]== undefined) o[itm]= 1;
        else ++o[itm];
    }
    for(var p in o) a[a.length]= {item: p, frequency: o[p]};
    return a.sort(function(a, b){
        return o[b.item]-o[a.item];
    });
}

测试:

var A= ["apples","oranges","oranges","oranges","bananas","bananas","oranges"];
A.byCount()

产地:

[ { frequency: 4, item: "oranges" }, { frequency: 2, item: "bananas"}, {frequency: 1, item: "apples"} ]

修改

正如Bergi在评论中指出的那样,做return o[b.item]-o[a.item];完全过于复杂,毫无意义。 return b.frequency - a.frequency;本来会更好。

答案 1 :(得分:1)

您可以通过执行以下操作来包含频率并简化代码:

&#13;
&#13;
Array.prototype.byCount = function() {
  var o = {};

  this.filter(function(el) { return el; }).forEach(function(el) {
      o[el] = (o[el] || 0) + 1;
  });

  return Object.keys(o).map(function (key) {
      return { key: key, occurrences: o[key] };
  }).sort(function(a, b) {
    return b.occurrences - a.occurrences;
  });
}

console.log(JSON.stringify([1, 2, null, 9, 9, undefined, 9, 9, 1, 3, 1, 1, 9, 2].byCount()));
&#13;
&#13;
&#13;

结果:

[{"key":"9","occurrences":5},
 {"key":"1","occurrences":4},
 {"key":"2","occurrences":2},
 {"key":"3","occurrences":1}]

如果你有Lo-Dash可用,你可以更干净地做到这一点:

&#13;
&#13;
Array.prototype.byFreq = function () {
  var grouped = _.groupBy(_.compact(this)),
      pairs = _.map(grouped, function (vals, key) { 
          return { key: key, occurrences: vals.length }
      }),
      sorted = _.sortBy(pairs, function (pair) { 
          return -pair.occurrences 
      });
  return sorted;
};

console.log(JSON.stringify([1,2,9,9, null, 9,9,1,3, undefined, 1,1,9,2].byFreq()));
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果您想将出现次数添加到值中,您可以在最后将它们放在一起:

return a.sort(function(a, b){
    return o[b]-o[a];
}).map(function(v) {
    return {value: v, count: o[v]}
});

或立即将它们放入数组中并调整比较函数:

for (var p in o)
    a.push({value: p, count: o[p]});
return a.sort(function(a, b){
    return a.count-b.count;
});