Anish Sinha
Anish Sinha

Reputation: 305

What is the best way to fix this triple-nested ternary operator?

I have a code snippet that sorts an array of objects. Each of the objects looks something like:

{
      "id": "60ff9eb7c793c6197dae5d42",
      "matches": 1,
      "timestamp": "2021-07-27T05:46:52.469Z",
      "likes": 23
}

I have a triple nested ternary expression that sorts them first by matches, then by likes, then by the timestamp. The code is below.

        bestMatches.sort((a, b) =>
          a.matches < b.matches
            ? 1
            : a.matches === b.matches
            ? a.likes < b.likes
              ? 1
              : a.likes === b.likes
              ? a.timestamp.getTime() < b.timestamp.getTime()
                ? 1
                : -1
              : -1
            : -1
        );

What is the best way to convert this to "good" code? I had a lot of difficulty using if/elses in this case, and I know that nesting ternary expressions is bad practice. As always, if you take the time to answer or attempt to answer this question, thank you for your time.

Upvotes: 0

Views: 124

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

Subtract to get the difference between the matches, then the likes, then the times.

bestMatches.sort((a, b) => (
  (b.matches - a.matches) ||
  (b.likes - a.likes) ||
  (b.timestamp.getTime() - a.timestamp.getTime())
));

Upvotes: 3

Related Questions