Sidechair

array.binary_search_leftmost()

Browse the reference

Searches an ascending array and returns the index of the first copy of a value, or of the nearest smaller item.

Try it in the editor

When the value is present, the lowest index holding it is returned. When it is absent, the result is the index of the closest item below it, which is where a lower neighbour sits.

If every item is larger than the value, the result is -1. The array has to be sorted ascending.

Syntax

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

Arguments

NameTypeDefaultDescription
idarray<int/float> or any array typerequiredThe array to search. It must already be sorted from low to high.
valseries int/float or series int/float/stringrequiredThe value to look for. If it is missing, the index of the nearest smaller item comes back.
sort_fieldconst int/stringnaThe field of a user-defined type to sort by when the array holds objects.

Returns

series int: The index of the first match, or of the nearest lower item.

Example

Pine ScriptClosest level below a priceOpen in editor
//@version=6
indicator("array.binary_search_leftmost: level below", overlay = false)
var levels = array.from(10.0, 20.0, 20.0, 30.0)
plot(array.binary_search_leftmost(levels, 20.0), "Value present")
plot(array.binary_search_leftmost(levels, 25.0), "Value absent")

See also

Runs on Sidechair