JavaScript provides built-in methods to sort arrays, making it convenient for developers to manipulate data. There are two primary ways to sort an array:
The default sort order is lexicographic (dictionary) order, based on the string representation of the elements. This means that when sorting an array of strings, numbers, or other elements, they are converted to strings and sorted according to their Unicode code points (UTF-16). For most cases, this default behavior is suitable when sorting an array of strings.
However, it's essential to be aware of potential pitfalls when sorting arrays of non-string elements, particularly numbers. The lexicographic order may not always produce the expected results for numbers:
Even to sort strings, the default sort order may give unexpected results. Not only does it not support localization, it also doesn't fully support Unicode, as it only considers UTF-16 code units. For example, in the code below, `"eΔ"` is surprisingly before and after `"éΔ"`. To guarantee that the sorting is reliable and remains as such in the long run, it is necessary to provide a compare function that is both locale and Unicode aware - typically `String.localeCompare`.
\[~ann.campbell.2] Assign for review and completion
=== on 28 Apr 2015, 13:28:08 Ann Campbell wrote:
Double-check my changes, please [~linda.martin]
Also, do you plan to raise this on all arrays, or limit it to when you can tell the array contains numbers?
=== on 29 Apr 2015, 09:16:26 Linda Martin wrote:
\[~ann.campbell.2] That's a good question. I think we'll do a first implementation and see what are the results and narrow the scope if too much FP shows up.