Reputation: 1356
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
Reputation: 2895
or maybe just
return (a.quantity < b.quantity) - (b.quantity < a.quantity)
Upvotes: 0
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
Reputation: 51
Yes those are equivalent
return (a.quantity > b.quantity) ? -1 : (a.quantity < b.quantity) ? 1 : 0;
Upvotes: 1