使用 lodash 或 underscorejs 查找字段的数组计数

Find array count of fields using lodash or underscorejs

本文关键字:数组 字段 查找 lodash underscorejs 使用      更新时间:2023-09-26

我有一个要求,获取数组中每种帐户类型的计数。我已经尝试了循环数组的正常方法,并为每个数组增加一个计数器account_type。你能帮我在 lodash 或下划线 js 中做同样的事情吗?

非常感谢

您的帮助。谢谢。

input_array = [
    {
        account_id: '4304bf0381140b8fcccbdddea3571a53facebook',
        account_type: 'facebook'
    },
    {
        account_id: '4304bf0381140b8fcccbdddea332434facebook',
        account_type: 'facebook'
    },
    {
        account_id: '5824fb40c4a97e21ef9715ea69c1cfb9twitter',
        account_type: 'twitter'
    },
    {
        account_id: '5824fb40c4a97e21ef9715ea432423twitter',
        account_type: 'twitter'
    },
    {
        account_id: '2c13790be20a06a35da629c71e548afexing',
        account_type: 'xing'
    },
    {
        account_id: 'd1376b07b144130c4f041e223dfb1197weibo',
        account_type: 'weibo'
    },
    {
        account_id: 'd1376b07b144130c4f041e223df4343weibo',
        account_type: 'weibo'
    }
]
output_array = [
    {
        type: "facebook",
        count: 2
    },
    {
        type: "twitter",
        count: 2
    },
    {
        type: "xing",
        count: 1
    },
    {
        type: "weibo",
        count: 2
    }
]

input_array.forEach(function(data){
    if(data.account_type=='facebook'){
        count++;//forfacebook
    }
});
您可以使用

countBy...

_.countBy(input_array, function(obj) {
    return obj.account_type;
});
您可以使用

filter()

var arrLen = _.filter(input_array, function(obj){
    console.log(obj)
    return obj.account_type === "facebook"
  }).length;