从数组中返回值并按频率返回事件 [英] Return values from array and occurences by frequency

查看:91
本文介绍了从数组中返回值并按频率返回事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个代码

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];
    });
}

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

This is almost what i need except that it does not return the number of occurences with the value.

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

I tried to rewrite it, but i always fail at the sorting part.

感谢您的帮助

推荐答案

这应该做您想要的:

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;会更好.

Doing return o[b.item]-o[a.item]; is completely overcomplicated an pointless as Bergi points out in comments. return b.frequency - a.frequency; would have been better.

这篇关于从数组中返回值并按频率返回事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆