关闭

js数组按某一项统计(排序、取最多最少)

109人阅读 评论(0) 收藏 举报
分类:

比如如下数据data,inputer_code一一对应inputer,找出inputer最多的那个

<script>
    var data=[
        {id: "148",input_time: "2016-03-01 15:18:26",inputer: "张三",inputer_code: "003"},
        {id: "151",input_time: "2016-03-01 19:49:42",inputer: "诺一",inputer_code: "001"},
        {id: "152",input_time: "2016-03-01 19:49:42",inputer: "张三",inputer_code: "003"},
        {id: "153",input_time: "2016-03-01 19:51:01",inputer: "诺一",inputer_code: "001"},
        {id: "154",input_time: "2016-03-01 19:52:04",inputer: "李四",inputer_code: "004"},
        {id: "155",input_time: "2016-03-03 19:52:04",inputer: "诺一",inputer_code: "001"}
    ];

    if(data.length>0){
        //inputers存放编码:姓名,number存放编码:出现次数
        var inputers={},number={};
        for(var i in data){
            if(data[i].inputer_code!==''){
                if(!number[data[i].inputer_code]){
                    number[data[i].inputer_code]=1;
                }else{
                    number[data[i].inputer_code]++;
                }
                 inputers[data[i].inputer_code]=data[i].inputer;
            }
        }
        //numberSort存放 出现次数
        var numberSort=[];
        for(var i in number){
            numberSort.push(number[i]);
        }

        //排序后遍历(可能有次数一样的)
        var max=numberSort.sort(sortNumber).pop();
        //console.log(max);
        var maxCode='';
        for(var i in number){
            if(number[i]==max){
                maxCode=i;
                console.log(inputers[maxCode]);
            }
        }
    }

    function sortNumber(a,b)
    {
        return a - b;
    }

    </script>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:15807次
    • 积分:285
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:35篇
    • 译文:0篇
    • 评论:0条
    文章分类