November 13, 2023
sort() method. This guide will demonstrate the process using clean, idiomatic examples suitable for any level of engineering expertise.
Understanding the sort method
sort() method that allows for custom sorting logic via a comparator function. When sorting by a boolean property, this function can simply return the difference between the boolean values of two objects.
Sample object array
Consider an array of objects where each object has a boolean property named
Sorting the array
To sort by the
This will sort the array with false values first. To sort with true values first, reverse the operands:
Under the hood
The comparator function works by returning:
- A negative number if the first argument should come before the second.
- A positive number if the first argument should come after the second.
- Zero if they are considered equal.
false is coerced to
1 during subtraction, this results in the correct sorting order.
For a more explicit approach, especially when dealing with TypeScript or to make the code more readable, you can use a comparison that doesn't rely on coercion:
Working with TypeScript
In TypeScript, type safety adds robustness to the sorting function:
This ensures that the properties exist and are of the correct type before the sort operation.
How to Truncate Date in MySQL