Search code examples
reactjscomparison

How to sort a list with different outputs depending on multiple conditions. react


I am trying to sort a list of entrants depending on their scores. If the score are the same, I then want to sort them on another value.

So far I have setSortedEntrants(props.event.entrants.sort((a, b) => (a.score < b.score) ? -1 : 1));

which sorts the entrants on their current score. I want to add to this, so that if the scores match, I then want to sort those on another value a.scoreCard.back9Score vs b.scoreCard.back9Score

I have tried this but doest seem to be quite right

setSortedEntrants(props.event.entrants.sort((a, b) => (a.score < b.score) ? -1 : a.score === b.score ? a.scoreCard.back9Score < b.scoreCard.back9Score: -1 ? a.score > b.score : 1));

logic being,

1- if a.score is less than b.score, move up one
2 - if a.score equals b.score then if a.scoreCard.back9Score  is less than b.scoreCard.back9Score then move up one.
3 - otherwise if a.score > b.score move down one.

all values for score and scoreCardback9Score and numbers

Is there somewhere obvious I am going wrong.


Solution

  • the condition should be as follows. You put the right code indentation, then you can figure out the matching clauses of ternary operator.

            setSortedEntrants(props.event.entrants.sort((a, b) => 
                (a.score < b.score) ? 
                  -1 
                   : (a.score === b.score ? 
                         (a.scoreCard.back9Score < b.scoreCard.back9Score ? 
                         -1 
                         : 1)
                     : 1)
                );