I have a list of objects I wish to sort based on a field attr
of type string. I tried using -
list.sort(function (a, b) {
retur
list.sort((a, b) => (a.attr > b.attr) - (a.attr < b.attr))
Or
list.sort((a, b) => +(a.attr > b.attr) || -(a.attr < b.attr))
Casting a boolean value to a number yields the following:
true
-> 1
false
-> 0
Consider three possible patterns:
(x > y) - (y < x)
-> 1 - 0
-> 1
(x > y) - (y < x)
-> 0 - 0
-> 0
(x > y) - (y < x)
-> 0 - 1
-> -1
(Alternative)
+(x > y) || -(x < y)
-> 1 || 0
-> 1
+(x > y) || -(x < y)
-> 0 || 0
-> 0
+(x > y) || -(x < y)
-> 0 || -1
-> -1
So these logics are equivalent to typical sort comparator functions.
if (x == y) {
return 0;
}
return x > y ? 1 : -1;