mph85
mph85

Reputation: 1356

Ternary Operator - 3 conditions

I'd like to rewrite this with a ternary operator. I believe I need 2 operators.

if (a.quantity > b.quantity) {
      return -1;
  } else if (a.quantity < b.quantity) {
      return 1;
  } else {
      return 0;
  }

Ternary

return (a.quantity > b.quantity) ? -1 : (a.quantity < b.quantity) ? 1 : 0;

would this be the equivalent?

Upvotes: 3

Views: 4384

Answers (3)

RARE Kpop Manifesto
RARE Kpop Manifesto

Reputation: 2895

or maybe just

return (a.quantity < b.quantity) - (b.quantity < a.quantity)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386766

If you need the value for sorting, you could take the delta of the two values:

data.sort((a, b) => a.quantity - b.quantity); // ascending
data.sort((a, b) => b.quantity - a.quantity); // descending

Upvotes: 3

Yes those are equivalent

return (a.quantity > b.quantity) ? -1 : (a.quantity < b.quantity) ? 1 : 0;

Upvotes: 1

Related Questions