Sidechair

array.sort()

Browse the reference

Sorts an array of numbers or strings in place, ascending by default or descending when asked.

Try it in the editor

array.sort(a) puts the smallest item first; array.sort(a, order.descending) puts the largest first. Strings sort alphabetically by character code.

The array itself changes and nothing is returned. Sort a copy when the original order matters, or use array.sort_indices() to get the order without moving the items.

Syntax

Pine Script
array.sort(id: array<int/float/string>, order: series sort_order (optional)) -> void
array.sort(id: any array type, order: series sort_order (optional), sort_field: const int/string (optional)) -> void
array.sort(order: series sort_order (optional)) -> void
array.sort(order: series sort_order (optional), sort_field: const int/string (optional)) -> void

Arguments

NameTypeDefaultDescription
idarray<int/float/string> or any array typerequiredThe array to reorder in place, numbers or strings, by the order argument.
orderseries sort_orderorder.ascendingorder.ascending or order.descending.
sort_fieldconst int/stringnaThe field of a user-defined type to sort by when the array holds objects.

Returns

Nothing.

Remarks

  • On Sidechair: na items always end up last, in ascending and descending order alike.
  • On Sidechair: the sort_field argument for arrays of user-defined types is not applied yet.

Example

Pine ScriptRank the last 5 volumesOpen in editor
//@version=6
indicator("array.sort: volume rank", overlay = false)
var vols = array.new_float()
array.push(vols, volume)
if array.size(vols) > 5
    array.shift(vols)
ranked = array.copy(vols)
array.sort(ranked, order.descending)
plot(array.get(ranked, 0), "Largest of 5")
plot(array.get(ranked, -1), "Smallest of 5", color.gray)

See also

Runs on Sidechair