Sort array UTF-8 with Javascript

 

Sort arrays with JavaScript is a very common feature that web programmers run. However, there are times when we want to order takes tildes , eñes or any spelling of another alphabet .

When this happens, the usual sorting method () sort does not work since we last sorts. Consider an example:


var myarray = ['Álex', 'Juan', 'José', 'Antonio', 'Carlos'];<font></font>
myarray.sort(); // Queda ordenado como Antonio, Carlos, José, Juan, Álex<font></font>


For these characters need a specific function to sort that could become our method sort () if our usual alphabet characters takes Unicode . To do the sorting UTF-8 need to do the following:

var myarray = ['Álex', 'Juan', 'José', 'Antonio', 'Carlos'];<font></font>
myarray.sort(function(a,b){return a.localeCompare(b);}); // Queda ordenado como Álex, Antonio, Carlos, José, Juan<font></font>

Comments

Popular posts from this blog

Coronavirus symptoms: what are they and should I call the doctor?

6 Big Reasons to Learn Even a Little HTML & CSS

Ads