带计数的组数组 [英] Group Array with count

查看:86
本文介绍了带计数的组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列包含多个属性的项目.属性之一是标签数组.获取这些项目中使用的所有标签并按这些标签在这些项目上使用的次数排序的最佳方法是什么?我一直在尝试强调js,但没有得到预期的结果.

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

我的数据示例:

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

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

所以我正在尝试获取{tag1, 2}{tag2, 1}{tag3, 1}

更新:我的标签包含一个ID和一个名称.我正在尝试按这些ID分组

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

推荐答案

您可以简单地使用reduce操作来做到这一点.例如

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

这篇关于带计数的组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆