In this article, we’ll delve into the array.sort_indices() function, its syntax, and practical applications through an example.
Syntax
The syntax for array.sort_indices()
is as follows:
array.sort_indices(id, order) → array<int>
Arguments:
id
(array): The array object to be sorted.order
(series sort_order): Specifies the sorting order. It can be eitherorder.ascending
ororder.descending
. This argument is optional, with the default setting beingorder.ascending
.
Example
Let’s break down a practical example to better understand how array.sort_indices()
functions:
//@version=5 indicator("array.sort_indices") sampleArray = array.from(5, -2, 0, 9, 1) sortedIndexArray = array.sort_indices(sampleArray) // [1, 2, 4, 0, 3] indexLowestValue = array.get(sortedIndexArray, 0) // 1 lowestValue = array.get(sampleArray, indexLowestValue) // -2 plot(lowestValue)

Walkthrough of Code
- Creating and Sorting the Array:
sampleArray = array.from(5, -2, 0, 9, 1)
: Creates an array with mixed integer values.sortedIndexArray = array.sort_indices(sampleArray)
: Generates an array of indices (sortedIndexArray
) that indicates the order in which elements ofsampleArray
should be accessed for a sorted sequence.
- Accessing Sorted Values:
indexLowestValue = array.get(sortedIndexArray, 0)
: Retrieves the index of the smallest value fromsortedIndexArray
, which is1
in this example.lowestValue = array.get(sampleArray, indexLowestValue)
: Uses the index to access the smallest value fromsampleArray
, yielding-2
.
- Visualization with
plot
:plot(lowestValue)
: Plots the lowest value in the array, which is-2
, on the chart.
Key Features and Takeaways
- Function Usefulness: The
array.sort_indices()
function is particularly valuable for scenarios where the original array’s structure must remain intact, and a sorted order is required for analysis or decision-making processes. - Syntax and Application: This function supports sorting of integer, float, and string arrays, providing flexibility across different use cases. The optional
order
argument allows for both ascending and descending sorts, catering to varied analytical needs. - Practical Example: The provided example demonstrates how to use
array.sort_indices()
to identify and plot the smallest value in an array. This approach can be extended to various analytical tasks, such as finding the highest, lowest, or specific percentile values in a data set.