SortArray()

Summary

Sorts the elements of an array.

Changes

In Version 6.0/2012 added Omit Missing and Compare Macro options.

Syntax

new_array = SortArray(array my_array [, array options])

Argument Contents
my_array The array to be sorted
Option Type Contents
Ascending Boolean If "True" (the default) the elements are sorted in ascending order; if "False" the elements are sorted in descending order
Compare Macro String Name of a macro that will be called to compare elements in the array when sorting
Omit Missing Boolean If "True" missing values will not be included in the returned array; if "False" (the default) missing values will be included
Unique Boolean If "True" will return a list of unique values, as determined by the element sorted first in the array; default is "False"

Returns

An array containing the sorted elements of my_array.

Notes

  • The options array is an optional argument.

  • If an array element is itself an array, the sort is performed using the value of the first element in the array.

  • SortArray() sorts arrays with numeric or string contents.

  • If the array contains elements of different types, the nulls are sorted to the beginning, followed by the numbers, then the strings. The behavior of other types is undefined, but will not return an error.

  • The compare macro will be called with 2 elements of the array as parameters and should return a negative number if the first element should come before the second, a positive number if the first should come after the second, or 0 if they are equivalent

Examples

new1 = SortArray({"Smith", "Jones", "Franklin"})
// new1 = {"Franklin", "Jones", "Smith"})
new2 = SortArray({{"Smith", 42}, {"Jones", 59}, {"Franklin", 21}})
// new2 = {{"Franklin", 21}, {"Jones", 59}, {"Smith", 42}})
new3 = SortArray({{42,"Smith"}, {59, "Jones"}, {21,"Franklin"}})
// new3 = {{21,"Franklin"}, {42,"Smith"}, {59,"Jones"}})
x = {5, 2, 1, 6, 4, 3}
x = SortArray(x) // now x = {1, 2, 3, 4, 5, 6}
x = {1, 5, 2, 1, 6, 4, 3, 2}
x2 = SortArray(x, {{"Unique","True"}, {"Ascending","False"}}) // x2 = {6,5,4,3,2,1}

See Also

Function Summary
CompareArrays() Compares two arrays, element by element
CopyArray() Makes a copy of the array, including nested sub-arrays, to any depth
ReverseArray() Returns a new array, with the same elements as the input array, but in the reverse order