Home » Array Functions » Understanding the array.sort_indices() Function in Pine Script

Understanding the array.sort_indices() Function in Pine Script

Photo of author
Published on

In this article, we’ll delve into the array.sort_indices() function, its syntax, and practical applications through an example.


The syntax for array.sort_indices() is as follows:

array.sort_indices(id, order) → array<int>


  • id (array): The array object to be sorted.
  • order (series sort_order): Specifies the sorting order. It can be either order.ascending or order.descending. This argument is optional, with the default setting being order.ascending.


Let’s break down a practical example to better understand how array.sort_indices() functions:

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

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 of sampleArray should be accessed for a sorted sequence.
  • Accessing Sorted Values:
    • indexLowestValue = array.get(sortedIndexArray, 0): Retrieves the index of the smallest value from sortedIndexArray, which is 1 in this example.
    • lowestValue = array.get(sampleArray, indexLowestValue): Uses the index to access the smallest value from sampleArray, 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.

Leave a Comment