How to Sort an Array Alphabetically in JavaScript
Table of Contents
Arrays are a great data structure for storing a collection of items in a single variable.
Oftentimes, the array will not be in alphabetical order but you need it in that order.
In this post, we'll learn how to sort an array alphabetically in JavaScript.
How to sort an array alphabetically in JavaScript
Let's start with an array that is not in alphabetical order.
JAVASCRIPTconst array = ["c", "a", "b"];
console.log(array);
BASH[ "c", "a", "b" ]
To sort this array, we will use the built-in sort
method.
This method takes a callback function as an argument and sorts the array based on the return value of the callback function.
If the callback function returns a negative number, the first element will be sorted before the second element.
Let's use the localeCompare
method to sort the array.
JAVASCRIPTconst array = ["c", "a", "b"];
array.sort((a, b) => a.localeCompare(b));
console.log(array);
BASH[ "a", "b", "c" ]
This works so elegantly because the localeCompare
method returns a negative number if a
is before b
and a positive number if a
is after b
, which is exactly what the sort
method expects.
This also works if you are working with an array of objects:
JAVASCRIPTconst array = [
{ name: "c" },
{ name: "a" },
{ name: "b" }
];
array.sort((a, b) => a.name.localeCompare(b.name));
console.log(array);
BASH0: {name: 'a'}
1: {name: 'b'}
2: {name: 'c'}
Either way, you end up with an array in alphabetical order which you can use further in your program.
Conclusion
In this post, we learned how to sort an array alphabetically in JavaScript.
Simply use the sort
method on the element, either directly or on an element's property, to tell the method how to order the elements.
Thanks for reading and happy coding!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Express
- How to Serve Static Files with Nginx and Docker
- How to deploy a MySQL Server using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js