Javascript - Array Reverse and Sort

Introduction

The reverse() method simply reverses the order of items in an array.

Demo

var values = [1, 2, 3, 4, 5];
values.reverse();
console.log(values);       //5,4,3,2,1

Result

Here, the array's values are initially set to 1, 2, 3, 4, and 5.

Calling reverse() on the array reverses the order to 5, 4, 3, 2, 1.

The sort() method puts the items in ascending order.

The sort() method calls the String() casting function on every item and then compares the strings to determine the correct order.

This occurs even if all items in an array are numbers:

var values = [0, 1, 5, 10, 15];
values.sort();
console.log(values);    //0,1,10,15,5

Even though 5 is less than 10, the string "10" comes before "5" when doing a string comparison.

To fix this, the sort() method allows you to pass in a comparison function that indicates which value should come first.

A comparison function accepts two arguments and returns

  • a negative number if the first argument should come before the second,
  • a zero if the arguments are equal, or
  • a positive number if the first argument should come after the second.

Demo

function compare(value1, value2) {
    if (value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
    } else {//  w ww  .  ja v  a  2s  . c om
        return 0;
    }
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
console.log(values);    //0,1,5,10,15

Result

The comparison function could produce results in descending order if you simply switch the return values like this:

Demo

function compare(value1, value2) {
    if (value1 < value2) {
        return 1;
    } else if (value1 > value2) {
        return -1;
    } else {// w w w  .  ja  va 2s .  co  m
        return 0;
    }
 }

var values = [0, 1, 5, 10, 15];
values.sort(compare);
console.log(values);    //15,10,5,1,0

Result

Exercise