Home  »  CodeGuidesProgrammingSnippetsTechnology   »   How to Sort String Alphabetically in JavaScript

How to Sort String Alphabetically in JavaScript

Posted: October 3, 2022 | by Michael Bright

Use this to sort string alphabetically in JavaScript:

arr.sort(function(a, b) {
    return a === b ? 0 : a < b ? -1 : 1;
});

function sortAlphabeticalOrder(arr) {
  return arr.sort((a, b) => a < b ? -1 : 1)
}

sortAlphabeticalOrder(["a", "d", "c", "a", "z", "g"]);

// returns:
// [ 'a', 'a', 'c', 'd', 'g', 'z' ]

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.