Press ESC to close

JavaScript sort

0 1869

In this article we will talk about the JavaScript sort method, which is useful for sorting the elements of an array.

The syntax of the sort() method is as follows: array.sort().

You can also indicate a comparison function for which the syntax becomes: array.sort(comparison function).

The comparison function is therefore optional and therefore the sorting takes place based on the value of the Unicode characters.

Now let’s do some practical examples of use.

JavaScript sort – first example

Sort an array of strings in ascending order.

So, first let’s create our example array:

var objectsSchools = ['pencil', 'eraser', 'sharpener'];

Then, with the sort method we sort it, then displaying the result in the browser console.


But be careful! If the initials of the names are not all uppercase or lowercase, the ordering may not be what you want.

In fact, the Unicode encodings for example of the letter a or A are different binary sequences.

Furthermore, if we try to sort an array made up of numbers, we will not have the desired result. We will discuss this in detail in the next example.

JavaScript sort – second example

Sort an array of numbers with the sort() method.

First we provide our array of numbers:

var numbers = [4,1,6,8,9,62];

Then let’s try to sort it with JavaScript sort method:


The result obtained, visible in the browser console, will be: array(6) [1, 4, 6, 62, 8, 9]. Therefore the ordering is not correct.

In order to use the sort method with numbers then it is necessary to use a function that makes a comparison between the numbers themselves.

So in this case we use the JavaScript sort method with this syntax: array.sort(comparison function).

The comparison function returns a negative, zero, or positive value. This value depends on the comparison between two adjacent values.

function (a, b) {return a – b}

If a is less than b then the result is negative and therefore a is sorted before b. If a is greater than b the result is negative and therefore b is sorted before a. Finally, if it is 0 it means that a and b are equal and therefore it is indifferent to write one number or the other first.

Here is the simple algorithm that allows you to sort a numeric array.

var numbers = [4,1,6,8,9,62];

numbers.sort(function (a, b) {
  return a - b;


In this lesson we talked about the JavaScript sort method and how to sort arrays of strings and numbers. In the next few lessons we will cover other methods on arrays in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Other stories

JavaScript reverse

Next Story

JavaScript map

Previous Story