TypeScript Helper Functions for Sorting
I'm not a huge fan of the Array.sort() method in JavaScript. When I want to sort an array of some random data type based on non-trivial criteria, I find it tedious to write the body of the compareFn argument to derive a comparable value from each of two arguments, compare those values myself, and then return -1, 1, or 0 as appropriate.
Below are some helper functions I like to use when sorting complicated data in TypeScript. The first is a compare() function that takes care of returning -1, 1, or 0 based on the two input values, and the second is a generic sortBy() function that accepts an array and a function to derive a comparable value from each item in the array.
Some notes:
I've added function overloads so that the
compare()function can only be used to compare either a pair of numbers or a pair of strings. Likewise, thesortBy()function has overloads that only acceptcompareByarguments which return either numbers or strings.The
sortBy()function passes the return value ofarray.sort(). This means thatsortBy()sorts arrays in place and returns a reference to the input array. You may wish to implement atoSortedBy()function that usesArray.toSorted().