使用lodash或下划线js查找数组中字符串元素的出现次数 [英] Find number of occurences of string elements in an Array using lodash or underscore js
本文介绍了使用lodash或下划线js查找数组中字符串元素的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个以下格式的数组:
I have an array in the following format:
var array = [
{ id: '555weibo' },
{ id: '578weibo' },
{ id: '111facebook' },
{ id: '123facebook' },
{ id: '145facebookpage' },
{ id: '145facebookpage' },
{ id: '766facebook' },
{ id: '242facebook' },
{ id: '432twitter' },
{ id: '432exing' }
];
我需要找到 facebook $ c $的出现次数c>,
twitter
, xing
,以及 weibo
里面的那个阵列。
例如:
I need to find the number of occurrences of facebook
, twitter
, xing
, and weibo
inside that array.
eg:
{
weibo: 2,
facebook: 6,
twitter: 1,
xing: 1
}
我搜索过一个解决方案,但似乎没有任何工作。
I've searched for a solution, but nothing seems to work.
以下代码未给出预期结果。非常感谢您的帮助。谢谢。
The following code doesn't give the expected result. Your help is much appreciated. Thank you.
var filtered = _.map(diff, function(value, key) {
return { id: key, count:value };
});
推荐答案
使用下划线:
var services = ['weibo', 'facebook', 'twitter', 'xing'];
var result = _.map(services, function(service){
var length = _.reject(array, function(el){
return (el.id.indexOf(service) < 0);
}).length;
return {id: service, count: length};
});
这篇关于使用lodash或下划线js查找数组中字符串元素的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文