JavaScript capitalization method

Noticed something potentially strange using the JavaScript method sort(). Given the following array:

var arr = ['Aaa',
'CUSTREF',
'Copy a template',
'Copy of Statementsmm',
'Copy1 of Default Email Template',
'Copy11',
'Cust',
'Statements',
'zzzz'];

Calling sort by this array:

console.log(arr.sort());

Productivity:

["Aaa", "CUSTREF", "Copy a template", "Copy of Statementsmm", "Copy1 of Default Email Template", "Copy11", "Cust", "Statements", "zzzz"] 

It is right? i.e. CUSTREFlisted first, is it because of its capital letters?

+3
source share
5 answers

It is right. Strings are sorted binary using the ordinal values ​​of the characters themselves.

For a case insensitive type, try the following:

arr.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if( a == b) return 0;
    return a < b ? -1 : 1;
});
+6
source

, - . , ASCII, Γ€ ΓΆ, String.localeCompare(). .

arr.sort(function (a, b) {
    return a.localeCompare(b);
});
+4

, Unicode. (it = 'U' )

.sort(function(a,b) { return (a.toLowerCase() < b.toLowerCase()) ? -1 : 1;});

+1

, (, ASCII), , , , - -

0

U (U + 0055) Unicode, o (U + 006F), sort U o. sort :

arr.sort(
    function(a, b){
        if (a.toLowerCase() < b.toLowerCase()) return -1;
        if (a.toLowerCase() > b.toLowerCase()) return 1;
        return 0;
    }
);
0
source

All Articles