【问题标题】:Count the length of messages from the same user [duplicate]计算来自同一用户的消息长度[重复]
【发布时间】:2018-04-19 20:36:13
【问题描述】:

我有一个名为 users 的数组,其中包含一个对象,如下所示:

'user': {
    'name': name,
    'msg': msg          
}

有可能在该数组中,一个用户被多次列出。 我想统计他所有消息的长度(msg)。

我是这样尝试的:

score = [];
for (i of users) {
    for (s of score) {
        if (s.name === i.user.name) {
            score.push({
                'name': i.user.name,
                'counter': i.user.msg.length
            });
        }
        else {
            s.counter = s.counter + i.user.msg.length;
        }
    }       
}

还包含一个对象的数组score 应该只包含唯一用户。所以它们不应该被列出两次。

无论如何,这不起作用,我对我的代码不是很满意,因为必须有更好、更简单的解决方案。

【问题讨论】:

  • 显示你的预期输出
  • 如果数组 score 有唯一用户,为什么不先将其转换为一个带有 users.unique_id 或 users.name(如果名称唯一)的字典?那么只需要循环array=users就可以得到你想要的结果。

标签: javascript


【解决方案1】:

您可以使用reduce 将分数转换为所有唯一值的映射。 一旦你有了那张地图,如果你愿意,你可以把它转换成一个数组。

const users = [
  {
    name: 'user1',
    msg: 'hello',
  },
  {
    name: 'user1',
    msg: 'hello2',
  },
  {
    name: 'user2',
    msg: 'world',
  },
  {
    name: 'user2',
    msg: 'world2',
  },
  {
    name: 'user3',
    msg: 'foo',
  },
];

const scores = users.reduce((scores, {name, msg}) => {
  if (!scores[name]) {
    scores[name] = { name, counter: 0 };
  }
  scores[name].counter += msg.length;
  return scores;
}, {});

// Now convert to an array if you want
console.log(Object.entries(scores));

【讨论】:

    【解决方案2】:

    score 可以使用对象而不是数组,并使用 user.name 作为键:

    const score = {};
    
    for (const user of users) {
      if (score[user.name]) {
        score[user.name].counter += user.msg.length;
      } else {
        score[user.name] = {
          name: user.name, 
          counter: user.msg.length,
        }
      }
    }
    

    【讨论】:

    • 很抱歉在这里打扰你,但你为什么删除that answer
    • 好吧,当我被否决时,我认为有问题,所以我删除了它。确实有一个错误(多出一行),现在修复并取消删除它。仍然不确定为什么会否决:/
    • 我的猜测是有人因为质量低劣而对问题投了反对票,而因为回答了一个糟糕的问题而对答案投了反对票。不要把反对票看得太严重,他们会判断“有用”而不是“正确性”——如果你认为你的答案有用,不要删除它并忽略反对票(如果有错误,评论应该指出)。我会回答完全一样的:-)
    猜你喜欢
    • 2011-06-09
    • 1970-01-01
    • 2021-09-09
    • 2013-06-15
    • 2015-05-09
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多