sort Method (Windows Scripting - JScript)

 

Returns an Array object with the elements sorted.

Syntax

arrayobj.sort(sortFunction) 

Arguments

  • arrayObj
    Required. Any Array object.

  • sortFunction
    Optional. The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.

Remarks

The sort method sorts the Array object in place; no new Array object is created during execution.

If you supply a function in the sortFunction argument, it must return one of the following values:

  • A negative value if the first argument passed is less than the second argument.

  • Zero if the two arguments are equivalent.

  • A positive value if the first argument is greater than the second argument.

The following example illustrates the use of the sort method.

function SortDemo()
{
   // Create an array.
   var a = new Array("4", "11", "2", "10", "3", "1");
   
   // Sort in ascending ASCII order.
   // The array will contain 1,10,11,2,3,4.
   a.sort();

   // Sort the array elements numerically.
   // Use a function that compares array elements.
   // The array will contain 1,2,3,4,10,11.
   a.sort(CompareForSort);
}

// This function is used by the sort method
// to sort array elements numerically.
// It accepts two string arguments that
// contain numbers.
function CompareForSort(param1, param2)
{
   var first = parseInt(param1);
   var second = parseInt(param2);
   
   if (first == second)
      return 0;
   if (first < second)
      return -1;
   else
      return 1; 
}

Requirements

Version 2

Applies To: Array Object (Windows Scripting - JScript)

Change History

Date

History

Reason

March 2009

Modified example.

Information enhancement.

See Also

small Method (Windows Scripting - JScript)