由其他数组组成的数组中字符串出现的次数

时间:2019-04-30 21:57:30

标签: javascript arrays

我已经看过很多这个问题,但是当数组中包含其他数组时,其中的一个都不是。
我有一个带有程序名称的数组,这是一个看起来像的小例子:(我的实际数组有3000多个条目)

None

此数组来自一项调查,来自一个包含某些程序的多项选择问题:

  • Excel
  • 微软团队
  • 单词
  • PowerPoint
  • 访问
  • Outlook
  • 其他:__________

受访者可以选择任意数量,但也可以添加任何“自定义”值。

我需要计算受访者选择列出的每个程序的次数。还要将所有“未列出”的都计为“自定义”值。
我不知道是否需要遍历数组中的所有项目,然后为其中的每个数组进行另一个遍历。但是我当然不知道该怎么实现。
预先感谢!

1 个答案:

答案 0 :(得分:2)

一种方法是将列表变平,然后计算每个值,可以为此使用Array.prototype.flat()Array.prototype.reduce()

const values = [
  ["Excel", "Microsoft Teams", "Word"],
  ["Access", "PowerPoint", "Excel", "Microsoft Project"],
  ["Access", "Outlook", "Microsoft Project", "Microsoft Teams", "Word"],
  ["Access", "MS Paint", "PowerPoint", "Outlook", "Excel", "Microsoft Teams", "Word", "MS Planner"],
  ["PowerPoint", "Excel", "Microsoft Teams", "Word"],
  ["PowerPoint", "Excel", "Word"],
  ["Access", "MS Paint", "Skype", "PowerPoint", "Excel", "Microsoft Teams", "Word"],
  ["Access", "Outlook", "Excel", "Microsoft Teams", "Word"],
  ["PowerPoint", "Excel", "Microsoft Project"],
  ["Access", "PowerPoint", "Excel", "Microsoft Teams", "Word"],
  ["Access", "PowerPoint", "Excel", "Word"],
  ["MS Paint", "Skype", "PowerPoint", "Outlook", "Excel", "Microsoft Project", "Microsoft Teams"],
  ["Chess"]
];

const result = values.flat().reduce((acc, x) => {
  acc[x] = (acc[x] || 0) + 1;
  return acc;
}, {});

console.log(result);

如果您关心性能,并且想要删除平坦化步骤(创建第二个应用了reduce的数组),则只需对每个级别应用一次reduce两次,

const values = [
  ["Excel", "Microsoft Teams", "Word"],
  ["Access", "PowerPoint", "Excel", "Microsoft Project"],
  ["Access", "Outlook", "Microsoft Project", "Microsoft Teams", "Word"],
  ["Access", "MS Paint", "PowerPoint", "Outlook", "Excel", "Microsoft Teams", "Word", "MS Planner"],
  ["PowerPoint", "Excel", "Microsoft Teams", "Word"],
  ["PowerPoint", "Excel", "Word"],
  ["Access", "MS Paint", "Skype", "PowerPoint", "Excel", "Microsoft Teams", "Word"],
  ["Access", "Outlook", "Excel", "Microsoft Teams", "Word"],
  ["PowerPoint", "Excel", "Microsoft Project"],
  ["Access", "PowerPoint", "Excel", "Microsoft Teams", "Word"],
  ["Access", "PowerPoint", "Excel", "Word"],
  ["MS Paint", "Skype", "PowerPoint", "Outlook", "Excel", "Microsoft Project", "Microsoft Teams"],
  ["Chess"]
];

const result = values.reduce((acc, x) => {
  const counts = x.reduce((out, y) => ({ ...out, [y]: (out[y] || 0) + 1 }), {});
  Object.entries(counts).forEach(([key, count]) => {
    acc[key] = (acc[key] || 0) + count;
  });
  return acc;
}, {});

console.log(result);