@@ -384,7 +384,7 @@ The order became `1, 15, 2`. Incorrect. But why?
384384
385385** The items are sorted as strings by default.**
386386
387- Literally, all elements are converted to strings for comparisons. For strings, lexicographic ordering is applied and indeed ` "2" > "15" ` .
387+ Literally, all elements are converted to strings for comparisons. For strings, lexicographic ordering is applied and indeed ` "2" > "15" ` .
388388
389389To use our own sorting order, we need to supply a function as the argument of ` arr.sort() ` .
390390
@@ -431,7 +431,6 @@ By the way, if we ever want to know which elements are compared -- nothing preve
431431
432432The algorithm may compare an element with multiple others in the process, but it tries to make as few comparisons as possible.
433433
434-
435434```` smart header="A comparison function may return any number"
436435Actually, a comparison function is only required to return a positive number to say "greater" and a negative number to say "less".
437436
@@ -456,6 +455,22 @@ arr.sort( (a, b) => a - b );
456455This works exactly the same as the longer version above.
457456````
458457
458+ ````smart header="Use ` localeCompare ` for strings"
459+ Remember [ strings] ( info:string#correct-comparisons ) comparison algorithm? It compares letters by their codes by default.
460+
461+ For many alphabets, it's better to use ` str.localeCompare ` method to correctly sort letters, such as ` Ö ` .
462+
463+ For example, let's sort a few countries in German:
464+
465+ ``` js run
466+ let countries = [' Österreich' , ' Andorra' , ' Vietnam' ];
467+
468+ alert ( countries .sort ( (a , b ) => a > b ? 1 : - 1 ) ); // Andorra, Vietnam, Österreich (wrong)
469+
470+ alert ( countries .sort ( (a , b ) => a .localeCompare (b) ) ); // Andorra,Österreich,Vietnam (correct!)
471+ ```
472+ ````
473+
459474### reverse
460475
461476The method [arr.reverse](mdn:js/Array/reverse) reverses the order of elements in `arr`.
0 commit comments