本文介绍了JavaScript代码使用array.reduce()获取对象数组中对象的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var developers = [
    { name: "Joe", age: 23 ,overallLevel: "high"},
    { name: "Sue", age: 28 ,overallLevel: "advanced" },
    { name: "Jon", age: 32 ,overallLevel: "high" },
    { name: "Bob", age: 24 ,overallLevel: "high" },
    { name: "Bob", age: 20 ,overallLevel: "advanced" }
]

需要使用array.reduce()在提到的数组中对totalLevel进行计数 [高:3,高级:2]

Need count of overallLevel in the mentioned array using array.reduce() [high:3, advanced:2]

推荐答案

您可以将它们与一个对象一起计数.

You could just count them with an object.

var developers = [{ name: "Joe", age: 23, overallLevel: "high" }, { name: "Sue", age: 28, overallLevel: "advanced" }, { name: "Jon", age: 32, overallLevel: "high" }, { name: "Bob", age: 24, overallLevel: "high" }, { name: "Bob", age: 20, overallLevel: "advanced" }],
    overallLevel = developers.reduce(function (r, a) {
        r[a.overallLevel] = (r[a.overallLevel] || 0) + 1;
        return r;
    }, {});

console.log(overallLevel);

这篇关于JavaScript代码使用array.reduce()获取对象数组中对象的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:26