JavaScript Arrays

Sorting Javascript Arrays

You can sort alphabetically very easily. e.g.


var animals = ["giraffe", "fish", "toad", "aardvark"];
animals.sort();
// animals is now ["aardvark", "fish", "giraffe", "toad"]
    

Numerical sort requires a comparator function! You cannot use normal sort because "10" will come before "9". This is the case even if you specified numbers.


var numbers = [20, 10, 30, 9];
numbers.sort();
// numbers is now [10, 20, 30, 9]
    

Instead use a comparator function to help sort the array. This function should return a negative, zero, or positive number.


var numbers = [20, 10, 30, 9];
numbers.sort(function(a,b) {
  return a - b;
});
// numbers is now [9, 10, 20, 30]

Arrays and Nulls

Below is an example about nulls and arrays


  var arrayTest = new Array();
  arrayTest[0] = 'hello';
  arrayTest[3] = 'bye';
  var output = "arrayTest length: " + arrayTest.length;
  output += "\n";
  output += "0: " + arrayTest[0];
  output += "\n";
  output += "1: " + arrayTest[1];
  output += "\n";
  if (arrayTest[1] == null) {
      output += "arrayTest[1] is null\n";
  }
  output += "2: " + arrayTest[2];
  output += "\n";
  output += "3: " + arrayTest[3];
  output += "\n";

output now holds:


arrayTest length: 4
0: hello
1: undefined
arrayTest[1] is null
2: undefined
3: bye

Published: Sunday, 31 December 2006
Updated: Sunday, 26 June 2011