问题
W3CSchools has this example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Is this the most efficient way to sort strings in descending order in Javascript?
Update
One of the answers is using localeCompare
. Just curious whether if we do reverse()
, will that work for all locales (Maybe this is a separate question - Just let me know in the comments)?
回答1:
If you consider
obj.sort().reverse();
VS
obj.sort((a, b) => (a > b ? -1 : 1))
VS
obj.sort((a, b) => b.localeCompare(a) )
The performance winner is : obj.sort().reverse()
.
Testing with an array of 10.000 elements,
obj.sort().reverse()
is about 100 times faster thanobj.sort( function )
, andobj.sort( function )
(usinglocalCompare
)
Performance test here : https://jsperf.com/reverse-string-sort/1
回答2:
Using just sort
and reverse
a
> Z
, that is wrong if you want to order lower cases and upper cases strings:
var arr = ["a","b","c","A","B","Z"];
arr.sort().reverse();
console.log(arr)//<-- [ 'c', 'b', 'a', 'Z', 'B', 'A' ] wrong!!!
English characters
var arr = ["a","b","c","A","B","Z"];
arr.sort((a,b)=>b.localeCompare(a))
console.log(arr)
Special characters using locales, in this example es (spanish)
var arr = ["a", "á", "b","c","A","Á","B","Z"];
arr.sort((a, b) => b.localeCompare(a, 'es', {sensitivity: 'base'}))
console.log(arr)
sensitivity in this case is base:
Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
回答3:
var arr = ["a","b","c","A","B","Z"];
arr.sort((a,b)=>b.localeCompare(a))
console.log(arr)
来源:https://stackoverflow.com/questions/52030110/sorting-strings-in-descending-order-in-javascript-most-efficiently