Dany Paredes
Danywalls | Angular ♥ Web

Danywalls | Angular ♥ Web

The Sort Method in Javascript Arrays

Photo by Sophie Elvis on Unsplash

The Sort Method in Javascript Arrays

How to Sort String and Numbers in JavaScript

Dany Paredes's photo
Dany Paredes
·Oct 17, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Sorting String
  • Sorting Numbers
  • Recap

I was helping one friend to build a sorting table with data in Typescript, and he found some weird behaviors in the process. Here we will learn what happens in javascript when using the sort method 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 doesn't work as expected, because, by default, it converts the values to strings to compare. The short story thinks like a dictionary "abandon", "abandoned" goes first, then "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

We learned how to use the sort method with strings and numbers and use a comparison function to fit our needs.

 
Share this