If I am sorting two strings café and cafe is there a best practice to follow as to which letter comes first? I tested localeCompare in javascript and café comes before cafe but I don't understand why.
We have two ways to sort strings such as Using sort() method or Using Loop. On using sort() method, we are using a predefined method by JavaScript to sort array of strings. Sort() method is applicable only for alphabetic strings. Sort() method does not support array of numbers.
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.
When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. If the result is negative, a is sorted before b . If the result is positive, b is sorted before a .
Best practice is to sort without diacritics first, ie. cafe comes before café.
localeCompare
works by stripping the diacritics, so the sort order doesn't reflect the real words, since café is turned into cafe
You can read more about localeCompare here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With