根据条件属性排序对象

时间:2019-12-02 14:54:49

标签: 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)

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

2 个答案:

答案 0 :(得分:1)

您需要的是对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,取决于points是否等于要比较的值。

答案 1 :(得分:0)

您的方法正确。

您要传递给table.sort()函数的是compare function

实际上您已经向其传递了一个compare函数,但是您可以明显地增强该函数,例如:

const compareFunction = (a, b) => {
    if (a.points === b.points) {
        if (a.points_difference === b.points_difference) {
            return a.points_for < b.points_for ? 1 : -1
        }
        else {
            return a.points_difference < b.points_difference ? 1 : -1
        }
    }
    else {
        return a.points < b.points ? 1 : -1
    } 
}

然后,您只需传递此函数即可进行如下排序:table.sort(compareFunction)