### 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

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.