首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用减缩和扩展运算符JS返回附加属性?

使用减缩和扩展运算符JS返回附加属性?
EN

Stack Overflow用户
提问于 2022-05-18 20:23:41
回答 1查看 29关注 0票数 -2

我正在使用下面的减少功能来计算一个球员名字被提到多少次,然后根据谁被提到的最少来列出他们。

我试图用我的对象返回第二个属性[`${value.subtitles[0].name} + ${index}`] : value.subtitles[0].url并对其进行排序。然而,这并不是正确的排序。当只返回第一个属性[value.title]: (acc[value.title] || 0) + 1,时,一切都按预期工作。但第二个属性使其排序不正确。它应该是基于标题属性值的排序,该属性值是一个整数,表示该播放机被提到多少次,从大多数到最少。为什么会发生这种情况?

谢谢你的帮助!

代码语言:javascript
复制
const players = [
  {
    "title": "Mike",
    "titleUrl": "https://mikegameplay",
    "subtitles": [
      {
        "name": "Mike Channel",
        "url": "https://channel/mike"
      }
    ]
  },
  {
    "title": "Cindy",
    "titleUrl": "https://cindy",
    "subtitles": [
      {
        "name": "Cindy Channel",
        "url": "https://channel/cindy"
      }
    ]
  },
  {
    "title": "Mike",
    "titleUrl": "https://mike",
    "subtitles": [
      {
        "name": "Mike Channel",
        "url": "https://channel/mike"
      }
    ]
  },
  {
    "title": "Haley",
    "titleUrl": "https://Haley",
    "subtitles": [
      {
        "name": "Haley Channel",
        "url": "https://channel/haley"
      }
    ]
  },
  {
    "title": "Haley",
    "titleUrl": "https://Haley",
    "subtitles": [
      {
        "name": "Haley Channel",
        "url": "https://channel/haley"
      }
    ]
  },
  {
    "title": "Haley",
    "titleUrl": "https://Haley",
    "subtitles": [
      {
        "name": "Haley Channel",
        "url": "https://channel/haley"
      }
    ]
  }
]
代码语言:javascript
复制
const counts = players.reduce((acc, value, index) => ({
   ...acc,
   [value.title]: (acc[value.title] || 0) + 1,
   [`${value.subtitles[0].name} + ${index}`] : value.subtitles[0].url
}), {});

const sortedValues = [];

for (const value in counts) {
    sortedValues.push([value, counts[value]]);
};

sortedValues.sort((a, b) => b[1] - a[1]);

console.log(sortedValues)
EN

回答 1

Stack Overflow用户

发布于 2022-05-18 20:52:53

尝尝这个

代码语言:javascript
复制
var groupBy = function (xs, key) {
  return xs.reduce(function (rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

var pl = groupBy(players, "title");
console.log(pl);

let sortable = [];
for (var item in pl) {
  sortable.push([item, pl[item].length, pl[item][0].subtitles[0].url]);
}

sortable.sort(function (a, b) {
  return b[1] - a[1];
});

console.log(JSON.stringify(sortable));

结果

代码语言:javascript
复制
[["Haley",3,"https://channel/haley"],["Mike",2,"https://channel/mike"],["Cindy",1,"https://channel/cindy"]]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72295523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档