Quick Way to Sort Arrays Alphabetically in JavaScript

Profile pictureRocktim Saikia/1 min read

We can very easily sort an array of strings in javascript using the String.prototype.localeCompare() method with the .sort() method of Array.

const array = ['adam', 'john', 'dan', 'mike', 'rock', 'anwar'];

const sortedArray = array.sort((a, b) => a.localeCompare(b));
console.log(sortedArray);
// ['adam', 'anwar', 'dan', 'john', 'mike', 'rock'];