Array.sort

Sorts the elements of an array.
Method of Array

Syntax

sort(compareFunction)

Parameters

Parameter Description
compareFunction Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

Description

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.
If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:
If compareFunction(a, b) is less than 0, sort b to a lower index than a.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.
If compareFunction(a, b) is greater than 0, sort b to a higher index than a.
So, the compare function has the following form:

To compare numbers instead of strings, the compare function can simply subtract b from a:

MetaScript uses a stable sort: the index partial order of a and b does not change if a and b are equal. If a's index was less than b's before sorting, it will be after sorting, no matter how a and b move due to sorting.

Example

See also

Array.join, Array.reverse

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.