
Posted on • Originally published atadamlacombe.com on
How to sort an array alphabetically
String.localeCompare()
If you're working with a relatively small array, you could uselocaleCompare().
constarr=[{name:"Orange"},{name:"Banana"},{name:"Carrot"},{name:"Apple"}];// [{"name":"Apple"},{"name":"Banana"},{"name":"Carrot"},{"name":"Orange"}]console.log(arr.sort((a,b)=>a.name.localeCompare(b.name)));
Intl.Collator()
If you're working with a large array, I would recommend usingIntl.Collator() for performance reasons.
constarr=[{name:"Orange"},{name:"Banana"},{name:"Carrot"},{name:"Apple"}];constcollator=newIntl.Collator();// [{"name":"Apple"},{"name":"Banana"},{"name":"Carrot"},{"name":"Orange"}]console.log(arr.sort((a,b)=>collator.compare(a.name,b.name)));
Benchmarks
1,000 strings
Here is abenchmark where we're sorting an array of 1,000 strings. As you can see,Intl.Collator() is 25% faster thanlocaleCompare().
25 strings
Here is abenchmark where we're sorting an array of only 25 strings. In this case,localeCompare() is 13% faster thanIntl.Collator().
Top comments(12)

“This is how sorting works in all applications”
Umm no.
“I cannot imagine why would you want to sort any other way”
How about sorting user last names? Usernames? Emails? For directory listing? Literally any string you would like to maintain locale specific sorting.

@rtivital Take this array of german strings for example:['Bären', 'küssen', 'Käfer', 'Ähnlich', 'Äpfel']
Sorting it using the method you provided will result in["Bären", "Käfer", "küssen", "Ähnlich", "Äpfel"]
which isn't correct.
The sorted array should look like["Ähnlich", "Äpfel", "Bären", "Käfer", "küssen"]
There is a reason these locale functions exist.

I think you’re missing the point of locale specific sorting.
Can you fork my sandbox and show me where the sorting is not correct?

- LocationWaterbury, VT
- WorkWeb Developer at Interactive Training
- Joined
Interesting. I see your point. iPhone definitely sorts things differently than I would expect though. That may be because each app manifest indicates its language so they're able to separately sort russian and then english apps.
I created anothercodepen that sorts['Я', 'ю', 'б', 'а', 'а', 'z', 'b']
usingIntl.Collator(['ru', 'en'])
which results in["а", "а", "б", "ю", "Я", "b", "z"]
.
Check out the documentation onLocale negotiation

Correct. I made a quick codepen showing the difference when sorting some characters from the German alphabetcodepen.io/adamlacombe/pen/ZEOezeq...
For further actions, you may consider blocking this person and/orreporting abuse