Group Array with count

浪子不回头ぞ 提交于 2020-07-03 04:42:47

问题


I have an array of items that contains several properties. One of the properties is an array of tags. What is the best way of getting all the tags used in those items and ordered by the number of times that those tags are being used on those items? I've been trying to look to underscore js but not getting the expected results.

return _.groupBy(items, 'tags');

Example of my data:

item1
 - itemName: item1
 - tags(array): tag1, tag2

item2
 - itemName: item2
 - tags(array): tag1, tag3

so I'm trying to get something like {tag1, 2}{tag2, 1}{tag3, 1}

Update: My tag contains a ID and a name. I'm trying to group by those IDs


回答1:


You can do this simply using a reduce operation. For example

var items = [{
  itemName: 'item1',
  tags: [
    {id: 'tag1', name: 'Tag 1'},
    {id: 'tag2', name: 'Tag 2'}
  ]
}, {
  itemName: 'item2',
  tags: [
    {id: 'tag1', name: 'Tag 1'},
    {id: 'tag3', name: 'Tag 3'}
  ]
}];

var tags = items.reduce((tags, item) => {
  item.tags.forEach(tag => {
    tags[tag.id] = tags[tag.id] || 0;
    tags[tag.id]++;
  });
  return tags;
}, {});

document.write('<pre>' + JSON.stringify(tags, null, '  ') + '</pre>');



回答2:


Map all tag arrays into a single array, and then countBy

var tags = _.flatten(_.map(items,d=>d.tags))
tags = _.countBy(tags)

Using underscores chain utility

var tags = _.chain(items).map(d=>d.tags).flatten().countBy().value();



回答3:


You may try this too:

var tagGroup =
  items.reduce(function(p, c){
      c.tags.map(function(tag){     
        p[tag] = p[tag] || {count:0};         
        p[tag].count++;
        return p;
      });

      return p;
  }, {});


来源:https://stackoverflow.com/questions/36975064/group-array-with-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!