js数组按某一项统计

数组如下所示,怎么统计出inputer最多的三个名字和重复的次数,求一个算法

var data=[
        {id: "001",inputer: "张三",inputer_code: "003"},
        {id: "002",inputer: "诺一",inputer_code: "001"},
        {id: "003",inputer: "张三",inputer_code: "003"},
        {id: "004",inputer: "诺一",inputer_code: "001"},
        {id: "005",inputer: "李四",inputer_code: "004"},
        {id: "006",inputer: "胡六",inputer_code: "001"},
        {id: "007",inputer: "张三",inputer_code: "003"},
        {id: "008",inputer: "诺一",inputer_code: "001"},
        {id: "009",inputer: "王五",inputer_code: "003"},
        {id: "010",inputer: "王五",inputer_code: "001"},
        {id: "011",inputer: "李四",inputer_code: "004"},
        {id: "012",inputer: "诺一",inputer_code: "001"}
    ];

谢谢!

阅读 2.4k
2 个回答
data.reduce(function(prev,next){ 
    prev[next.inputer] = (prev[next.inputer] + 1) || 1; 
    return prev; 
},{}); 

次数有了,接下来就简单了

const result = data.reduce((total, cur) => {
    total[cur.inputer] = total[cur.inputer] ? total[cur.inputer] + 1 : 1;
    return total
}, {})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题