I have found the following boolean sort:
const sorted = things.sort((left, right) => {
return Number(!!left.current) - Number(!!right.current);
});
Is this the correct way to sort booleans?
I have found the following boolean sort:
const sorted = things.sort((left, right) => {
return Number(!!left.current) - Number(!!right.current);
});
Is this the correct way to sort booleans?
You could use the difference of the values, casted to boolean.
The minus operator coerces both operands to number and returns a numerical value, which reflects the order as needed by Array#sort.
undefined values are sorted to the end and are never used for sorting callback.
var booleans = [0, true, 42, undefined, null, NaN, 'foo'];
booleans.sort((a, b) => Boolean(a) - Boolean(b)); // falsy values first
console.log(booleans);
booleans.sort((a, b) => Boolean(b) - Boolean(a)); // truthy values first
console.log(booleans);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Boolean(true), Boolean(false) - O.o!!, which is better done with Boolean.Boolean() is it isn't doing parsing/casing as may be traditionally expected in other languages. Its evaluating an expression (which most situations like this do in JS) just like an if statement, and returning the result as a bool. 'false' is a truthy value so returns true. Just wanted to provide a little more info for the benefit of the person asking the question.Yes, the best comparator in JavaScript to sort an booleans array is minus comparator, because in this case (mathematical procedure) all booleans (we have only false and true) will be casted into numbers.
You can read it in documentation from Array.sort() function:
compareFunction Optional
Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
It is an unicode code point value, which means it is a number.
Example
And I have to mention that you do not need an extra casting to a number like Number(!!boolean).
// We need two arrays to see the difference between
// ascending and descending order because the returned
// array is sorted in place, and no copy is made.
var things1 = [true, false, true, false, true],
things2 = [true, false, true, false, true];
var sorted_AscendingOrder = things1.sort(function(left, right)
{
return left - right
});
var sorted_DescendingOrder = things2.sort(function(left, right)
{
return right - left
});
console.log(sorted_AscendingOrder.join(', '));
console.log(sorted_DescendingOrder.join(', '));
But you could sort an booleans array without of any comparator like follows:
var things3 = [true, false, true, false, true];
// in Ascending Order
console.log(things3.sort().join(', '));
var things4 = [true, false, true, false, true];
// in Descending Order
console.log(things4.sort().reverse().join(', '));