Javascript sort array method

Sort

Sorts the elements of an array in place and returns the array.

Syntax

array.sort([compareFunction])

Example

The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without, then with, a compare function.

var stringArray = ["Blue", "Humpback", "Beluga"];
var numericStringArray = ["80", "9", "700"];
var numberArray = [40, 1, 5, 200];
var mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200];

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

// again, assumes a print function is defined
print("stringArray: " + stringArray.join() +"\n");
print("Sorted: " + stringArray.sort() +"\n\n");

print("numberArray: " + numberArray.join() +"\n");
print("Sorted without a compare function: " + numberArray.sort() +"\n");
print("Sorted with compareNumbers: " + numberArray.sort(compareNumbers) +"\n\n");

print("numericStringArray: " + numericStringArray.join() +"\n");
print("Sorted without a compare function: " + numericStringArray.sort() +"\n");
print("Sorted with compareNumbers: " + numericStringArray.sort(compareNumbers) +"\n\n");

print("mixedNumericArray: " + mixedNumericArray.join() +"\n");
print("Sorted without a compare function: " + mixedNumericArray.sort() +"\n");
print("Sorted with compareNumbers: " + mixedNumericArray.sort(compareNumbers) +"\n\n");

This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.

stringArray: Blue,Humpback,Beluga
Sorted: Beluga,Blue,Humpback

numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200

numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700

mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1,200,40,5,700,80,9
Sorted with compareNumbers: 1,5,9,40,80,200,700

DOWNLOAD SOLUTION HERE