Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 基于条件属性对对象排序_Javascript_Arrays_Sorting - Fatal编程技术网

Javascript 基于条件属性对对象排序

Javascript 基于条件属性对对象排序,javascript,arrays,sorting,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_

我正在调用一个包含一些运动数据的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)

但我正在努力实现这些其他条件。数据将始终是一个对象数组。谢谢你在这方面的帮助

你走的路是对的

传递给
table.sort()函数的是一个函数

事实上,您已经向它传递了一个比较函数,但是您可以明显地增强此函数,例如:

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
    } 
}
constcomparefunction=(a,b)=>{
如果(a点===b点){
如果(a.点数差===b.点数差){
返回a.points_表示

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

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

table.sort((a,b)=>{
如果(a点!==b点)返回b点-a点
如果(a点差异!==b点差异){
返回b.积分差-a.积分差
}
返回b.points\u for-a.points\u for

})
这是否回答了您的问题?太好了,谢谢!如果需要,可以更轻松地添加变量。