简体   繁体   中英

javascript `localeCompare` return different values

I am now working in javascript string sorting using localeCompare and my data will contain several null values too.

And i found a weird behavior with localeCompare when comparing string and null value. When comparing string value upto startswith a/A to n/N it working fine as below.

"n".localeCompare(null) // return -1;
"N".localeCompare(null) // return -1;

But after if i compare the null value with o/O to z/Z it returns 1

"o".localeCompare(null) // return 1;
"O".localeCompare(null) // return 1;

I know that localeCompare work with comparing Unicode but why the above behavior happens is there any reason?

localeCompare compares strings, as such anything passed to it will be converted to a string, and you'll get the same result from

"n".localeCompare("null") // return -1;
"o".localeCompare("null") // return 1;

because

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

MDN

which means

"null".localeCompare("null") -> will return 0 as it's the same string
"n".localeCompare("null") -> will return -1 as it comes before null "o".localeCompare("null") -> will return 1 as it comes after null

If you want a real-world comparer that can handle null values

Then, you are better off implementing something like this,

function stringComparer(a,b) {
  if(a && b)
    return a.localeCompare(b);
  else 
    // sort null and "" to bottom
    if(a)
      return -1;
    else if(b)
      return 1;
    else 
      return 0;
}

and using it to compare your values. Here is an example,

['Łove','Love',null,"",null,'kellogs','Kellogs','kellogs',null,"Lover","   ",'Man',"abc", "AAb", "Abc"].sort(stringComparer)

There is some room for improving this depending on how you want null, " " and "" values to sort in relation to each other. In the above implementation, " " will sort to the top while null and "" values will sort to the bottom.

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