How to Sort an Array Alphabetically in JavaScript


Sort an Array Alphabetically in JavaScript

In this article, we will look at sorting an array alphabetically in JavaScript. We will cover both arrays with strings and arrays with objects.

Sorting an Array with Strings

When sorting an array, we can use the sort method.

const unsortedList = ['Mary', 'Alfred', 'John'];
const sortedList = unsortedList.sort();

console.log(sortedList.toString()); // prints: Alfred,John,Mary

This is pretty simple. We only need to use the sort method without any parameters.

Beware of Casing

When sorting, the casing of the letters might give you some unexpected results.

Look at this example:

const unsortedList = ['Mary', 'alfred', 'John'];
const sortedList = unsortedList.sort();

console.log(sortedList.toString()); // prints: John,Mary,alfred

Here I changed alfred to start with a lower case character. As you can see, alfred is moved last in the array.

We can solve this by using an arrow function and compare the strings with the localeCompare function.

const unsortedList = ['Mary', 'alfred', 'John'];
const sortedList = unsortedList.sort((a, b) => a.localeCompare(b));

console.log(sortedList.toString()); // prints: alfred,John,Mary

As you can see, this solves the casing problem.

Sorting an Array of Objects Alphabetically

We will be using localeCompare for sorting objects as well.

The only change is that we are comparing the properties.

const unsortedList = [
    { name: 'Mary' },
    { name: 'alfred' },
    { name: 'John' }
];
const sortedList = unsortedList.sort((a, b) => a.name.localeCompare(b.name));

console.log(sortedList); // prints: [ { name: 'alfred' }, { name: 'John' }, { name: 'Mary' } ]

Rooney

I am a full-stack web developer with over 13 years of experience. I love learning new things and are passionate about JavaScript development both on the front-end and back-end.

Recent Posts