【问题标题】:How to sort a VueJS object in descending order of the number of occurrences?如何按出现次数的降序对 VueJS 对象进行排序?
【发布时间】:2019-10-25 01:11:08
【问题描述】:

我有一个动态对象,它由用户选择的出现次数组成。对象如下所示:

{ "Excitement": 2, "Competence": 3, "Sophistication": 1 }

这是函数:

rankFactors() {
      const headers = this.headers;
      var counts = {};
      for (var i = 0; i < headers.length; i++) {
        var num = headers[i];
        counts[num] = counts[num] ? counts[num] + 1 : 1;
      }
      return counts;
 }

如何对该对象进行排序以使其始终按降序排列?这样我就可以将其打印为“前 3 名”列表。

这是我的 CodeSandbox:https://codesandbox.io/embed/vue-template-mzi03

要复制,只需选择个性特征,从几个标题中选择多个选项。

【问题讨论】:

标签: arrays object vue.js


【解决方案1】:

我想我会这样做:

rankFactors() {
  const headers = this.headers;
  const counts = {};

  for (const header of headers) {
    counts[header] = (counts[header] || 0) + 1;
  }

  const factors = Object.keys(counts).map(header => {
    return {
      name: header,
      count: counts[header]
    }
  });

  factors.sort((a, b) => b.count - a.count);

  return factors;
}

第一阶段与你的非常相似,建立一个计数对象。这是一个用于收集这些计数的简单数据结构,但是一旦该阶段完成,它就不是处理排序的好选择。为此,我们最好使用数组。

接下来它将对象转换为对象数组,每个对象的形式为{name: 'Excitement', count: 2}。然后根据计数对该数组进行排序,然后返回。如果您只想要前 3 名,可以输入 .slice(0, 3)

【讨论】:

  • 这很完美,正是我想要实现的目标!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2019-11-25
  • 1970-01-01
  • 2021-07-26
相关资源
最近更新 更多