DEV Community

Simon Ugorji

Posted on • Updated on

How does the sort method work in JavaScript?

In my article today, I will show you how the sort method (`Array.prototype.sort()`) works in JavaScript, the logic behind it, and how you can use it to sort an array.

INTRODUCTION

The Array prototype `sort()` is used to sort elements in an array depending on the logic provided and then returns the reference to the same array, now sorted.

The default order of the `sort()` method is ascending and it works by converting the array elements into strings, then arranging them according to each character's Unicode code point value.

The `sort()` method accepts a callback function and this function will contain some logic that will be used to properly sort the array.

WHAT WE WILL DO

I will make use of the `sort()` method on an array and then provide a callback function that will actually perform the sorting

If I am to sort an array of numbers `[3,4,5,2,1]` in ascending order, I will use the logic `( a > b )` to compare each element and it will return the element whose code point value is lower than the next, sorted.

According to Wise geek, a code point refers to a specific numerical value that signifies any individual character in a character set.

So this means that every character on your keyboard has a code point in the character set.

Now you may ask, "What then is a character set?"

Well, a character set is like a multilingual dictionary that explains to the computer which numbers correspond to which characters.

So the uppercase character "A" has a code point of "65" and the lowercase character "a" has a code point of "97" in the character set.

This means that if we were to sort an array of letters in ascending order, the uppercase letters get sorted first before the lowercase letters and if we were to sort an array of letters in descending order, the lowercase characters get sorted first before the uppercase letters.

This happens because of their code points in the character set.

That makes sense right? π

Let's see how we can get the code points of characters in JavaScript.

RETRIEVE THE CODE POINTS OF CHARACTERS

To retrieve the code point of a character in javascript, I will make use of the string method `codePointAt()` on the string.

``````//uppercase A
console.log("A".codePointAt())
//65

//lowercase a
console.log("a".codePointAt())
//97
``````

So you can see that an uppercase letter comes before a lowercase letter because of its code point in the character set.

Now let us try what we have learned so far on an array.

SORTING AN ARRAY

Recall that we talked about the sort method and the logic that we would use in its callback function to make it sort our array.

In my first example, I will sort the array in ascending order, and I will use the logic ( a > b ) in its callback function

``````//sort in ascending order
["a", "C", "b", "A", "c", "B"].sort( (a, b) => {
return (a > b)
})

//Array(6) [ "A", "B", "C", "a", "b", "c" ]

``````

So you can see that the array got sorted by arranging the uppercase letters first before the lowercase letters in ascending order.

In my second example, I will sort the array in descending order using the logic ( b > a ) in its callback function

``````//sort in descending order
["a", "C", "b", "A", "c", "B"].sort( (a, b) => {
return (b > a)
})

//Array(6) [ "c", "b", "a", "C", "B", "A" ]
``````

You can see that the array got sorted by arranging the lowercase letters first before the uppercase letters in descending order.

With my explanation, we can even sort an array containing the names of people in ascending order and it will sort it just fine

``````//sort in ascending order
["john", "jane", "jade", "joseph"].sort( (a, b) => {
return (a  > b)
})

//Array(4) [ "jade", "jane", "john", "joseph" ]
``````

It works by summing up the code points of each character in the string and then arranging them in ascending order.

This will give you a better view of what the computer does under the hood.

The code below calculates the sum of the code points of each character in an element of the array

``````let output = []

//function to calculate code point values
const calcCodePoint = (val) => {
//store the total code point number of a string
let totalCodePoint = 0
//get the code point total of the string
val.split('').forEach( (el) => totalCodePoint+=el.charCodeAt())
return output.push(totalCodePoint)
}

//loop through the array and calculate their code point values

//sort the result
output.sort( (a, b) => {
return (a - b)
})

//Array(4) [ 404, 414, 431, 649 ]
``````

So you can see that the element with a total code point of 404 (jade) was arranged first and the element with a total code point of 649 (joseph) was arranged last and this is how our array actually gets sorted. π

I hope you understand now.

MAKE NO MISTAKES

If you are trying to sort an array of strings containing letters, make sure that you have converted them to lowercase already using the string method `toLowerCase()` before sorting them.

Sorting an array like this will probably make you feel like the sort function is useless, but it isn't!

Take note of the capitalization in "John", "Jane", and "jOseph".

``````//sort in ascending order
["John", "Jane", "jade", "jOseph"].sort( (a, b) => {
return (a  > b)
})
//Array(4) [ "Jane", "John", "jOseph", "jade" ]
``````

It's a computer and it was programmed to calculate the code points of characters based on the character set before acting on it!

Also, do not try to sort an array containing strings and numbers because the result wouldn't be what you expect to see π

``````//sort in ascending order
["1", "3", "a", "4", "2", 5].sort( (a, b) => {
return (a > b)
})
//Array(6) [ "1", "2", "3", "4", "a", 5 ]

//sort in ascending order
[1, 2, "a", "4", "2", "80", "9"].sort( (a, b) => {
return (a > b)
})
//Array(7) [ 1, 2, "2", "4", "80", "9", "a" ]
``````

Mozilla Docs have an explanation for this;

In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order

So do not blame your computer or the JS Engine because you now have a clear understanding of characters and their code point numbers now and how they are sorted.

Well, numbers are not left out because you can sort them either in ascending or descending order and this brings to notice that the sort method converts the elements of the array to strings before acting on it and the reason why it is converted to a string is to get its code point number.

If I have the scores of students in my class in an array, I will sort them in ascending order like this;

``````//sort in ascending order
[344,500,222,132,90,50].sort( (a, b) => {
return (a > b)
})

//or
[344,500,222,132,90,50].sort( (a, b) => {
return (a - b)
})

//Array(6) [ 50, 90, 132, 222, 344, 500 ]
``````

The same goes for strings of numbers.

Because an array might contain strings of numbers, we will use the logic `(a - b)` to sort the array in ascending order, and if we wanted to sort the array in descending order, we will use the logic`(b - a)`.

This is the recommended way to sort an array containing numbers or strings of numbers.

Take a look at the difference below;

``````//β not recommended π

//sort in ascending order
["344",500, "222",132, "90", "50"].sort( (a, b) => {
return (a > b)
})
//Array(6) [ 132, "222", "344", "50", "90", 500 ]

// β recommended π

//sort in ascending order
["344",500, "222",132, "90", "50"].sort( (a, b) => {
return (a - b)
})
//Array(6) [ "50", "90", 132, "222", "344", 500 ]
``````

I hope you have learned something spectacular today.

It is recommended to use the logic `(a > b)` on strings depending on the order in which you want your results to appear and the logic `(a - b)` on numbers or strings of numbers depending on the order in which you want your results to appear.

IT'S FUN TIME

I have seen a lot of debate regarding this question.

"The chicken and the egg, which came first?" π

Well, I guess computer programmers gave us their opinion regarding this.

If I am to retrieve the Unicode code point of the emojis of an egg and chicken, this is the number I see

``````//code point of egg
console.log( "π₯".codePointAt() )
//129370

//code point of chicken
console.log( "π₯".codePointAt() )
//128037
``````

Looking at the result above, you might have guessed that the chicken came before the egg, and if I am to sort an array containing just these 2 elements, this will be the result.

``````//sort in ascending order
["π₯", "π₯"].sort( (a, b) => {
return (a > b)
})
//Array [ "π₯", "π₯" ]
``````

Well, as for me, I believe that the chicken came before the egg.

CONCLUSION

We have talked about the code point of characters and how every character on your keyboard has a code point in the character set of your computer.

We have also talked about how the `sort()` method works and the logic that it uses to be able to arrange array elements depending on our logic.

I also showed you some of the mistakes you should avoid making when trying to sort an array and lastly, the recommended way to sort an array of strings and an array of numbers.

EXTRA

I built and launched a validation library that you can use to validate your forms both client-side and server-side using validation rules, sophisticated regular expressions, and form input attributes

It's available for ReactJS, NodeJs, PHP, and Native Js.

Here is a link to the repository of the library

Octavalidate - JS | Getting Started

Octavalidate - JS: This JavaScript Library helps to validate your HTML forms using validation rules, sophisticated regular expressions and form input attributes

octagon-simon.github.io

I am open to both web development, and technical writing roles.