You want to sort a list of strings in JavaScript, but some of the strings are empty, and you want those to come last. localeCompare is your friend, but it places empty strings first.
The solution is a bit of boolean sweetness:
["foo", "", "bar"].sort((a, b) => a && b ? a.localeCompare(b) : !a - !b ); // [ "bar", "foo", "" ]
For instance, if a is empty but b is not, the else case in the ternary resolves to true - false
⇒ 1 - 0
⇒ 1
which means: put b before a.
Leave a Reply