2

I am calling an API with some sports data and i want to orgnise the json into decending order depending on how many 'points' they have. however if two players have the same points, then want to order them them by 'points difference', and if they have the same points difference, then order by 'points for'. for example a random json like so:

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}
]

Should be organised like this...

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}
]

i currently organise based on one property, like so:

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

but am struggling to implement these other conditions. the data will always be an array of objects. appreciate any help on this!

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
DevOps guy
  • 51
  • 1
  • 4
  • Does this answer your question? [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – Emile Bergeron Dec 02 '19 at 15:59

2 Answers2

1

What you need is the right modification of your compareFunction. I would suggest the following change:

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
})

With this, conditions are run in order. Fall from points to points_difference to points_for depending on if points, then points_difference are found equal for the values being compared.

jackthedev
  • 578
  • 5
  • 7
0

You are on the right way.

What you are passing to the table.sort() function is a compare function.

In fact you are already passing a compare function to it, but you can obviously enhance this function for example like this:

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
    } 
}

You then just pass this function to sort like this: table.sort(compareFunction)

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Bioaim
  • 928
  • 1
  • 13
  • 26