DEV Community

Discussion on: Sorting Arrays of Strings in JavaScript

Collapse
 
krofdrakula profile image
Klemen Slavič • Edited

There's a big caveat to this method of string sorting: it doesn't take Unicode and non-English alphabets into account. Depending on your application, you might want to consider using the String::localeCompare() instead which has built-in support for things like language-specific sort ordering, ignoring cases or diacritics:

const strings = ['č','é','A','b','Đ'];

const defaultSort = Array.from(strings).sort();

const simpleSort = Array.from(strings).sort((a, b) => a - b);

const localeSort = Array.from(strings).sort((a, b) => {
  return a.localeCompare(b, 'en', { sensitivity: 'base' });
});

console.log(defaultSort);
console.log(simpleSort);
console.log(localeSort);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
charlesmwray profile image
Charles Wray

Love this reply. It's exactly what I was looking for. I do want to comment that there is a typo in case someone else tries to use this like I did and it didnt work. In the localeSort variable assignment it should be

return a.localeCompare(b, 'en', { sensitivity: 'base' });

Collapse
 
ricardorien profile image
Ricardo Aguilar

Thanks! both anwser are awesome!

Collapse
 
maprangsoft profile image
Maprangsoft

thank you.