Find the number of occurrences of string elements in an array using lodash or underscore 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' } ]; 

I need to find the number of occurrences of facebook , twitter , xing and weibo inside this array. eg:

 { weibo: 2, facebook: 6, twitter: 1, xing: 1 } 

I was looking for a solution, but nothing works.

The following code does not give the expected result. Your help is greatly appreciated. Thanks.

 var filtered = _.map(diff, function(value, key) { return { id: key, count:value }; }); 
+6
source share
3 answers

Using underscore:

 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}; }); 
+4
source

Here you can do it with lodash:

 _.countBy(array, _.flow( _.method('id.replace', /^\d+/, ''), _.method('replace', /page$/, '') )); 
  • countBy () returns an object with count values. The keys are generated by the passed in the callback, so here you can analyze and manipulate the keys that you want to count.
  • flow () generates a function, usually for map() callbacks, etc. Arguments require an arbitrary number of functions. The input is filtered through each of these functions, and the result is returned. This is a powerful way to build callbacks because it easily moves / adds / removes it.
  • method () returns the function called on the given object. You want to replace the leading digits with a blank line here.
  • method() does the same thing except removing page from the end of the line. Note how there is no id prefix, as it simply passes the result of the function before it.
+11
source

You must specify the possible keys, since there is no way to guess them in the original array.

Here you do not need a library:

 var filtered = array.reduce(function(m,v){ for (var k in m) if (~v.id.indexOf(k)) m[k]++; return m; },{facebook:0, weibo:0, twitter:0, xing:0}); 

Demonstration

+8
source

Source: https://habr.com/ru/post/987656/


All Articles