javascript - 根据条件属性对对象进行排序

标签 javascript arrays sorting

我正在调用一个带有一些运动数据的 API,我想将 json 组织成降序,具体取决于他们有多少“积分”。但是,如果两名球员的积分相同,则要按“积分差”对他们进行排序,如果他们的积分差相同,则按“积分”排序。例如像这样的随机 json:

let table = [
{team_name: "D", points: 10, points_difference: 45, points_for: 52},
{team_name: "B", points: 12, points_difference: 38, points_for: 60},
{team_name: "C", points: 10, points_difference: 45, points_for: 52},
{team_name: "A", points: 12, points_difference: 40, points_for: 60}
]

应该这样组织...

let table = [
{team_name: "A", points: 12, points_difference: 40, points_for: 60},
{team_name: "B", points: 12, points_difference: 38, points_for: 60},
{team_name: "C", points: 10, points_difference: 45, points_for: 52},
{team_name: "D", points: 10, points_difference: 45, points_for: 50}
]

我目前基于一个属性进行组织,如下所示:

table.sort((a, b) => b.points - a.points)

但我正在努力实现这些其他条件。数据将始终是一个对象数组。感谢对此的任何帮助!

最佳答案

您需要的是对您的 compareFunction 进行正确的修改。我建议进行以下更改:

table.sort((a, b) => {
  if(a.points !== b.points) return b.points - a.points
  if(a.points_difference !== b.points_difference) {
    return b.points_difference - a.points_difference
  }
  return b.points_for - a.points_for
})

有了这个,条件就按顺序运行了。从 points 到 points_difference 到 points_for 取决于 if points,然后发现 points_difference 与被比较的值相等。

关于javascript - 根据条件属性对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59141432/

相关文章:

javascript - Mongoose .findOne 错误返回找到的模型?

javascript - 如何将整数的每一位存储在数组中

javascript - 如何在给定目标索引数组的情况下对数组进行就地排序?

list - 使用冒泡排序按长度对列表中的列表进行排序 - Haskell

javascript - 将 Angular 网格保存在本地存储中

javascript - 有没有办法通过频繁调用的API请求来控制useEffect结果?

Javascript根据数组本身找到二维数组中的最高值

具有 native JSON 支持的 MySQL 5.7 - 如何选择数组中存在特定值的行?

c++ - 在 C++ 中声明和删除此版本的二维数组

MySQL 从每个类别中选择前 N 个最便宜的产品