Understand How the Sort Method Operates on Javascript Arrays

How to Sort String and Numbers in JavaScript

I was assisting a friend in constructing a sorting table with data in Typescript and he ran into some odd behavior along the way. In this lesson, we will explore what occurs in Javascript when the sort method is used with strings and numbers.

Sorting String

The sort method helps us to sort the data. For example, we have a list of words to order alphabetic.

const words = [ 'a', 'd','c', 'b']
words.sort()
console.log(words) // ["a", "b", "c", "d"]

Excellent works! Let's add the "W".

const words = [ 'a', 'd','c', 'b', 'W']
words.sort()
["W", "a", "b", "c", "d"]

Something is weird; the W uppercase is at the beginning. It is because the default string sorting is case-sensitive.

We must pass a comparison function to the sort method to solve it. Inside, call two functions toLowerCase() and localeCompare() to compare case-sensitive.

words.sort((a,b) => a.toLowerCase().localeCompare(b.toLowerCase()));
//["a", "b", "c", "d", "W"]

MDN: The default sort order is ascending, built upon converting the elements into strings, then comparing their UTF-16 code unit value sequences.

Read more about the sort method in Arrays.

Perfect! It works. Let's continue with the numbers.

Sorting Numbers

We have a list of numbers to sort ascending using the sort method.

const loteryNumbers = [ 15, 44, 4, 33, 8]
loteryNumbers.sort()
console.log(loteryNumbers)
// [15, 33, 4, 44, 8]

The sort method isn't working properly, because it automatically converts the values to strings for comparison. It works in a similar way to a dictionary, so "abandon" would come before "abandoned" and "abbey".

abandon            
abandoned        
abbey
abbreviate

We solve it using a comparison function again in the sort method with two parameters and compare the values with the following logic:

  • If the first value is less, the second returns negative -1.

  • If they are equal, return 0

  • If the first is higher than the second, positive 1.

Something like:

 if(a > b) {
    return 1
 }
 if(a === b){
   return 0
 }
 if(a < b) {
   return -1
 }

The simplified version a - b comparison to cover all the scenarios:

loteryNumbers.sort((a,b) => a - b) //ascending [4, 8, 15, 33, 44]
loteryNumbers.sort((a,b) => b - a) //descending [44, 33, 15, 8, 4]

Perfect, we are sorting the numbers in descending and ascending ways.

Recap

This lesson discussed using the sort method in Javascript for strings and numbers. It covered how to order strings alphabetically, make sorting case-insensitive, and order numbers in ascending and descending order using comparison functions.