简体   繁体   中英

boolean sort for comparator in javascript

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?

Why don't just use - operator ?

 things = [{"current":true},{"current":false},{"current":true}] things.sort((left, right) => left.current - right.current); console.log(things); 

- will coerce both operands to Number automatically.

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; } 

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(', ')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM