Sorting an array

When working with arrays, sometimes you may want to sort the array. To sort an array, you can use JavaScript's sort () method. Suppose we want to sort the following list in alphabetical order:

  • Maryland
  • Arizona
  • California
  • New York
  • Virginia
  • Texas

To sort this list, we will create an array using the following JavaScript code:

var statesArr = new Array(6);
statesArr [0] = "Maryland";
statesArr [1] = "Arizona";
statesArr [2] = "California";
statesArr [3] = "New York";
statesArr [4] = "Virginia";
statesArr [5] = "Texas";

The above code creates an array called statesArr with 6 elements. To sort this array, use the sort () method as:

statesArr.sort();

With that statement, our array is sorted. The followings shows the complete JavaScript code and how to print the sorted array using a for loop:

<script language="javascript">
var statesArr = new Array(6);
statesArr [0] = "Maryland";
statesArr [1] = "Arizona";
statesArr [2] = "California";
statesArr [3] = "New York";
statesArr [4] = "Virginia";
statesArr [5] = "Texas";
statesArr.sort();
for (i = 0; i <= 5; i++)
{
document.write (statesArr[i] + "<br>");
}
</script>

The following shows the output of the sorted array: