首页 > 解决方案 > 显示每个标签出现的次数

问题描述

我有一个用户对象,我试图显示每个标签出现的次数。我在 ExaltedToast 代码中编辑

我期望的输出是:

测验:1

厌烦:1

结果:1

: 1

场合:2

..等等

我得到的输出是:

{"quis":1,"irure":1,"consequat":1,"ut":1,"occaecat":2,"esse":1,"qui":1,"in":1," duis":1,"officia":1,"ipsum":1,"incidudunt":2,"ex":1}

我的数组对象

const users = [
  {
    age: 21,
    eyeColor: "green",
    name: "Gregory Villarreal",
    company: "BLUPLANET",
    tags: ["quis", "irure", "consequat", "ut", "occaecat"],
  },
  {
    age: 39,
    eyeColor: "brown",
    name: "Bowman Jensen",
    company: "HOMETOWN",
    tags: ["esse", "qui", "in", "duis", "occaecat"],
  },
  {
    age: 35,
    eyeColor: "brown",
    name: "Berg Carson",
    company: "WRAPTURE",
    tags: ["officia", "ipsum", "incididunt", "incididunt", "ex"],
  },
];

到目前为止我的代码

// OLD CODE
// get the tags from the array
const userTags = users.map((user) => (user.tags));

// count the tag occurrences
const tagCount = userTags.reduce((obj, e) => {
    obj[e] = (obj[e] || 0) + 1;
    return obj;
  }, {});

// display the tag occurrences
let div = document.createElement('div');
div.innerHTML = JSON.stringify(tagCount);
document.body.appendChild(div);

//  CURRENT CODE
users.forEach((user) => {
    user.tags.forEach((tag) => {
        tagCount[tag] = (tagCount[tag] | 0) + 1;
    });
});

let div = document.createElement('div');
div.innerHTML = JSON.stringify(tagCount);
document.body.appendChild(div);

我有一个 JSBIN https://jsbin.com/leqeludahi/和一个代码片段

const users = [
  {
    age: 21,
    eyeColor: "green",
    name: "Gregory Villarreal",
    company: "BLUPLANET",
    tags: ["quis", "irure", "consequat", "ut", "occaecat"],
  },
  {
    age: 39,
    eyeColor: "brown",
    name: "Bowman Jensen",
    company: "HOMETOWN",
    tags: ["esse", "qui", "in", "duis", "occaecat"],
  },
  {
    age: 35,
    eyeColor: "brown",
    name: "Berg Carson",
    company: "WRAPTURE",
    tags: ["officia", "ipsum", "incididunt", "incididunt", "ex"],
  },
];

const tagCount = {};
users.forEach((user) => {
    user.tags.forEach((tag) => {
        tagCount[tag] = (tagCount[tag] | 0) + 1;
    });
});

let div = document.createElement('div');
div.innerHTML = JSON.stringify(tagCount);
// div.innerHTML = tagCount.join('\n');
document.body.appendChild(div);

标签: javascriptarraysobjectcounting

解决方案


您已经接近了,您只需要额外遍历数组中的标签,而不仅仅是将数组直接添加到对象中。

// Get the tags from the array
const userTags = users.map((user) => user.tags);

// Count the tag occurrences
const tagCount = userTags.reduce((obj, e) => {
    for (let tag of e) {
        obj[tag] = (obj[tag] || 0) + 1;
    }
    return obj;
}, {});

一个相当干净的解决方案是在forEach.

let tagCount = {};
users.forEach((user) => {
    user.tags.forEach((tag) => {
        tagCount[tag] = (tagCount[tag] | 0) + 1;
    });
});

推荐阅读