简体   繁体   中英

sort array lexicographically in javascript

Why does this code

["Q", "fP", "AQ", "L"].sort((a,b) => a.localeCompare(b))

give this result:

["AQ", "fP", "L", "Q"]

I thought it would give me this (and that's what I need):

["AQ", "L", "Q", "fP"]

All uppercase letters come before lower case letters chortle.ccsu.edu/java5/Notes/chap92/ch92_2.html

Don't use localeCompare() , just use sort() directly

 let myArray = ["Q", "fP", "AQ", "L"]; myArray.sort(); console.log(myArray);

Interestingly enough, the following works in NodeJS, but not in Browser JavaScript. This is because the ECMAScript standard doesn't dictate which sorting algorithm to use, so it's up the each browser and/or NodeJS to dictate

let myArray = ["Q", "fP", "AQ", "L"];
myArray.sort((a, b) => a > b);
console.log(myArray);

NodeJS Demo

https://repl.it/@AnonymousSB/SO53688028

Documentation

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11

Try this:

 let myArray = ["Q", "fP", "AQ", "L"]; myArray.sort((a, b) => a > b ? 1 : -1); console.log(myArray);

Don't use localeCompare() , just use sort() directly. As below:

["Q", "fP", "AQ", "L"].sort();

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