sort()  Array  instance method setterS2C Home  « Globals « Array « sort()

Description

Sorts the elements within an array.

Syntax

Signature Description
anArray.sort([sortOrderFunction])Sorts the elements within an array.

Parameters

Parameter Description
sortOrderFunctionSpecifies a function that designates a sort order.
If omitted sort will be done in lexographic order.

Examples

The code below creates an array then sorts it without a sort order function.


/*
 Create an array of names.
 Sort elements.
 sortNames = ['Fred', 'Jed', 'Ned', 'Neil', 'Ted'] after sort().
 */
var sortNames = ['Fred', 'Ned', 'Ted', 'Jed', 'Neil'];
alert(sortNames);
sortNames.sort();
alert(sortNames);

Press the button below to action the above code:


The code below creates an array then sorts it using a sort order function.


/*
 Create an array of numbers.
 Sort elements using a function.
 sortNumbers = [1, 2, 3, 4, 5] after sort().
 */
var sortNumbers = [5, 1, 3, 4, 2];
alert(sortNumbers);
sortNumbers.sort(function(a, b) {  
  return a - b;  
});
alert(sortNumbers);

Press the button below to action the above code:


Related Tutorials

JavaScript Intermediate Tutorials - Lesson 1 - Arrays

go to home page Homepage go to top of page Top