简体   繁体   中英

Can you help me to understand how works sort() in Javascript?

i know in general how works this method in javascript, but i haven't understand how order an array with UNICODE...

EXAMPLE:

var fruits = [
["caldera Cuicocha",1],
["Telica",2],    
];

I believed that the order did not change because the letter "c" preceding the letter "t"...

but with

fruits.sort();

the output is this:

//Telica
//caldera Cuicocha

would you be so kind as to explain to me why? the calculation for unicode characters as happens?

sort compares strings by default. This means, ["caldera Cuicocha",1] and ["Telica",2] are both converted to strings first: "caldera Cuicocha,1" and "Telica,2" . Converting an Array to string is equivalent to join ing it with , .

Now you have correctly noticed that the sort is based on Unicode. Capital letters come before lower case letters, however:

Char  Hex-Code

   A  41
   B  42
   …  …
   Z  5A
   …  …
   a  61
   b  62
   …  …
   z  7A

sort sorts the array as expected with "caldera Cuicocha,1" coming after "Telica,2" .

Here is a sorting function which will do what you want:

function sortfunc(a, b) {
    var cmpa = a[0].toLowerCase(), cmpb = b[0].toLowerCase();
    return cmpa < cmpb ? -1 : cmpa > cmpb ? +1 : 0;
}

In other words, take the first element of each of the two arrays, lower case it, then compare and return -1, +1, or 0, which is what sort expects back from its sort function. Then:

fruits.sort(sortfunc)

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