简体   繁体   中英

JavaScript's sort method handling of capital letters

Noticed something potentially odd with JavaScript's sort() method. 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 on this array:

console.log(arr.sort());

Yields:

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

Is this correct? ie. CUSTREF is listed first, is this because of it's capital letters?

That is correct. The strings are being sorted in a binary fashion, using the ordinal values of the characters themselves.

For a case-insensitive sort, try this:

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

You are correct, it is because of capital letters. If you are sorting strings which might have non ASCII characters such as ä and ö you should use String.localeCompare() . This also fixes the capital letter problem.

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

Yes, It has a higher Unicode value. (it = the 'U' in the first word)

you maybetter use

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

如果你看一下他们对字符进行编码的方式(例如ASCII表),你会看到,大写字母的值较低,小写一个,所以是 - 这是因为大写字母

Since U (U+0055) has a lesser Unicode value than o (U+006F), a case-sensitive sort will always place U before o . For a case-insensitive sort , you should try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM