我正在调用一个带有一些运动数据的 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/