Search code examples
javascriptsortinglocale

Remove accents in an array of strings


I have an array of strings, like so

let array = ['Enflure', 'Énorme', 'Zimbabwe', 'Éthiopie', 'Mongolie']

I want to sort it alphabetically, so I use array.sort(), and the result I get is :

['Enflure', 'Mongolie', 'Zimbabwe', 'Énorme', 'Éthiopie']

I guess the accents are the problems here, so I would like to replace the É with an E all over my array.

I tried this

for (var i = 0; i < (array.length); i++) {
    array[i].replace(/É/g, "E");
}

But it didn't work. How could I do this?


Solution

  • You could use String#localeCompare.

    The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

    The new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation dependent.

    var array = ['Enflure', 'Mongolie', 'Zimbabwe', 'Énorme', 'Éthiopie'];
    
    array.sort((a, b) => a.localeCompare(b));
    
    console.log(array);