Sort an Array of Strings in JavaScript, TypeScript or Node.js

Sorting arrays of data is an everyday use case in applications. For example, you want to display a list of names in alphabetical order and allow the user to toggle the sorting from ascending to descending and vice-versa.

This tutorial shows you how to sort an array of strings in JavaScript.

Node.js Series Overview

Sort a String Array in JavaScript

JavaScript comes with the Array#sort method. This sort method allows you to provide a comparator callback. The return value of the comparator function determines the sorting.

Notice: the Array#sort method in JavaScript mutates the array. Please create a copy of your array if you want (or need) to keep the original sorting of your data.

Sort Using String.localeCompare()

JavaScript string value implement the localeCompare method. This method returns a number indicating whether the comparison string comes before, after, or is the same string value in sort order.

Here’s an example of sorting an array of words using accents, lowercase, and uppercase:

['réservé', 'RESERVE'].sort((a, b) => {
  return a.localeCompare(b)

// ['RESERVE', 'réservé']

You can also pass a reference “locale” as the second argument and an options object as the third argument:

['réservé', 'RESERVE'].sort((a, b) => {
  return a.localeCompare(b, 'en', { sensitivity: 'base' })

// ['réservé', 'RESERVE']

The configuration options allow you to control the sorting based on your language requirements.

Sort Strings in Ascending Order

Another way to sort string values is a comparison and returning the desired integer value. When sorting ascending, you should return -1 to tell the comparator that the first value comes before the reference.

The following example uses case-insensitive sorting by lowercasing before comparing them. Using a lowercase comparison keeps the alphabetical order:

['marcus', 'Christian', 'Norman'].sort((a, b) => {
  return a.toLowerCase() < b.toLowerCase()
    ? -1
    : 1

// ['Christian', 'marcus', 'Norman']

The sorting is different when comparing the given string values case-sensitively:

['marcus', 'Christian', 'Norman'].sort((a, b) => {
  return a < b ? -1 : 1

// ['Christian', 'Norman', 'marcus']

Sort Strings in Descending Order

You can also sort a string array in descending order returning a 1 when the first value should come after the reference value:

['Marcus', 'Christian', 'Norman'].sort((a, b) => {
  return a.toLowerCase() < b.toLowerCase()
    ? 1
    : -1

Enjoy sorting string arrays!

Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.