Sorting strings in descending order in Javascript (Most efficiently)?

亡梦爱人 提交于 2020-01-31 04:16:10

问题


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 than obj.sort( function ), and obj.sort( function ) (using localCompare)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!