# Sorting Elements in an Array Alphabetically in JavaScript

Sharing is Caring

There’s a lot of reasons why you may want to sort an array, often it is done to make things easier for the user of the application to understand the data. Arrays are normally sorted to be in ascending order (or alphabetical).

For the most part, with arrays sorting alphabetically can be done really easily by calling sort() or reverse().

``````'use strict'

const myArray = ['a', 'e', 'c', 'q', 'z']
console.log(myArray.sort())

// returns [ 'a', 'c', 'e', 'q', 'z' ]``````

To reverse the array we would do this:

``````'use strict'

const myArray = ['a', 'c', 'e', 'q', 'z']
console.log(myArray.reverse())

// returns [ 'z', 'q', 'e', 'c', 'a' ]``````

With numbers this unfortunately breaks because it looks at them as if they were strings so running the following code results in numbers being in the wrong order.

``````'use strict'

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(myArray.sort())

// returns [ 1, 10, 2, 3, 4, 5, 6, 7, 8, 9 ]
``````

As you can see 10 is showing up second in the list, when it should actually be at the end. To fix this we need to provide a comparator function.

``````'use strict'

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(myArray.sort((a, b) => {
return a - b
}))

// returns [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]``````
Sharing is Caring