loading...
Cover image for Sorting an Array in JavaScript

Sorting an Array in JavaScript

monicafidalgo profile image 🦊 Atomic Fox ・2 min read

In JavaScript it is possible to sort the items of an array with the sort() method.

What the sort() method does is that sorts the values as strings. The sort can be either alphabetic or numeric and ascending or descending.

var animals = ["Horse", "Rabbit", "Dog", "Cat"];

animals.sort();

//["Cat", "Dog", "Horse", "Rabbit"]

⚠️ Keep in mind that this method changes the original array.

When sorting numbers, the method will have a different behavior, because if numbers are sorted as strings, "35" is bigger than "100", because "3" is bigger than "1".

In order to fix this, we can provide a compare function.

Syntax

array.sort(compareFunction)

According to MDN, The compare function specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

This function can also provide an alternative sort order. The function should return a negative, zero, or positive value, depending on the arguments.

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

To compare numbers instead of strings, the compare function can simply subtract b from a.

function compareNumbers(a, b) {
  return a - b;
}

Sort numbers in an array in ascending order:

var numbers = [100, 54, 12, 42, 30, 23, 1];

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

//  [1, 12, 23, 30, 42, 54, 100]

Sort numbers in an array in descending order:

var numbers = [100, 54, 12, 42, 30, 23, 1];

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

//  [100, 54, 42, 30, 23, 12, 1]

Note that now we are subtracting b-a instead of a-b.

And what about, sorting strings in an array in descending order?

We can do that by applying the reverse() method after the sort() method

var animals = ["Horse", "Rabbit", "Dog", "Cat"];

animals.sort();
animals.reverse();

// ["Rabbit", "Horse", "Dog", "Cat"]

or we can do it by changing the logic of the compare function and pass it to the sort( ) method

var animals = ["Horse", "Rabbit", "Dog", "Cat"];

animals.sort(function (a, b) {
    if (a > b) {
        return -1;
    }
    if (b > a) {
        return 1;
    }
    return 0;
});

// ["Rabbit", "Horse", "Dog", "Cat"]

To more cases, check the MDN documentation

Banner photo: Soraya Irving

Posted on Mar 7 by:

monicafidalgo profile

🦊 Atomic Fox

@monicafidalgo

I’m Mónica, a Front end developer graduated in marine biology. We are always on time to reinvent ourselves.

Discussion

markdown guide
 

Great post, I'm making a series that explain javascript in a funny easy way and the first post which I'm preparing right now is about the array methods.
And you should add the beginner tag