Sidechair

array.sort_indices()

Browse the reference

Returns the positions of an array's items in sorted order, leaving the array itself untouched.

Try it in the editor

The result lists indexes, not values: its first entry is the position of the smallest item, its second entry the position of the next smallest, and so on. Pass order.descending to start from the largest.

Use it to rank one array and then read a parallel array in that order, for example names ordered by their scores.

Syntax

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

Arguments

NameTypeDefaultDescription
idarray<int/float/string> or any array typerequiredThe array to rank. It is left as it is; the result lists the positions in sorted order.
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

array<int>: A new array<int> of positions in the order the items would take after sorting.

Remarks

  • On Sidechair: na items are ranked last in either direction, and the sort_field argument is not applied yet.

Example

Pine ScriptWhich of the last 4 bars closed highestOpen in editor
//@version=6
indicator("array.sort_indices: best bar", overlay = false)
var win = array.new_float()
array.push(win, close)
if array.size(win) > 4
    array.shift(win)
order_ = array.sort_indices(win, order.descending)
plot(array.get(order_, 0), "Index of highest close")
plot(array.size(win), "Window size")

See also

Runs on Sidechair