Sorting an array in Pine Script

Sorting is an essential feature of arrays in programming, as it allows the user to organize data easily. In this article, I’ll show you how you can quickly sort arrays in Pine Script.

First, let’s define an array we want to sort:

x = array.from(5, 2, 0, 1, 3)

The primary function to sort arrays in Pine Script is array.sort. You can simply pass your array to this function, and Pine Script will sort elements of your array in ascending order. Your array will be sorted “In Place”. You shouldn’t reassign it to the new variable.

array.sort(x)

To check the result of this sorting, I’ll plot the array in a label:

if (barstate.islast)
    label.new(bar_index, high, str.tostring(x))

You can see that it works well. We get an array sorted in ascending order:

To sort the array in descending order, you can simply use the second optional argument “order”:

array.sort(x, order.descending)

This will oppositely sort the array:

Sort_indices function

Another exciting function in Pine Script I have to show you is “array.sort_indices”. With its help, you can easily find the lowest/highest/the second lowest/etc. elements. Let’s see how it works with an example:

y = array.sort_indices(x)

So as you can immediately see, it doesn’t work “in place” as the array_sort function but outputs another array. This array will represent indices for your array from the lowest to the highest value. If you print it you’ll see the following array:

It’s pretty easy to interpret these numbers. The first value is 2, which means that the lowest value in your array is located at a position with index = 2, and the last value is 0, which means that the largest value is the first in your array.


Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.