2015-06-19 2 views
0

У меня есть требование получить количество каждого типа учетной записи в массиве. Я пробовал обычный способ петли массива и увеличивать счетчик для каждого account_type. Не могли бы вы помочь мне сделать то же самое в lodash или underscore js.Найти количество массивов полей, использующих lodash или underscorejs

Ваша помощь очень ценится. Спасибо.

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

ответ

2

Вы можете использовать countBy ...

_.countBy(input_array, function(obj) { 
    return obj.account_type; 
}); 
0

Вы можете использовать filter()

var arrLen = _.filter(input_array, function(obj){ 
    console.log(obj) 
    return obj.account_type === "facebook" 
    }).length; 
Смежные вопросы