How to sort an array in JavaScript
Sorting an array in JavaScript is handy with sort
array method.
js
const names = ['Sojiro','åshKeys','Sakaßato','Ashok M A','Zin','Kenshin','Himura']const sortedNames = names.sort((a, b) => a.localeCompare(b))console.table(sortedNames)
The above gives the following sorted array in table format as we used console.table
.
js
/**┌─────────┬─────────────┐│ (index) │ Values │├─────────┼─────────────┤│ 0 │ 'åshKeys' ││ 1 │ 'Ashok M A' ││ 2 │ 'Himura' ││ 3 │ 'Kenshin' ││ 4 │ 'Sakaßato' ││ 5 │ 'Sojiro' ││ 6 │ 'Zin' │└─────────┴─────────────┘**/
Notice that we used localeCompare
as our sorting method. It is really useful for comparing strings from different locales. \O/
Tip: By default it takes it by the base of the letters irrespective of their locales as you can see in our example as well. ^_^