Skip to main content

array.sort(function)

Re-orders the items within an array

Availability

Device + Agent

Parameters

Name Type Description
function Function An optional data-comparison function

Returns

Nothing

Description

This method sorts the items within the target array into either a lowest-to-highest order or according to the results of an optional comparison function which may be passed to the method as a parameter. If the items are arrays, blobs, functions, objects and/or tables, they will be sorted by reference not value.

The optional comparison function should take two parameters: two values which will be compared in some way. It should return the value -1 if the first value should be placed before the second, or 1 if it should follow the second value. Return 0 if the two values are equivalent.

The method takes care of iterating over the target array’s items a sufficient number of times to ensure they are all correctly sorted.

Example Code

The first code snippet applies a simple sort, ordering the items numerically. The second example applies a custom sort function, comparing the array items to strings in a table — the table values are then used to order the strings, which would ordinarily be compared on the basis of the Ascii values of their component characters.