Sidechair

array.binary_search_rightmost()

Browse the reference

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

Try it in the editor

When the value is present, the highest index holding it is returned. When it is absent, the result is the index of the closest item above it, which is also the position at which the value would be inserted.

If every item is smaller than the value, the result is the array size. Sort the array first, or the answer means nothing.

Syntax

Pine Script
array.binary_search_rightmost(id: array<int/float>, val: series int/float) -> series int
array.binary_search_rightmost(id: any array type, val: series int/float/string, sort_field: const int/string (optional)) -> series int
array.binary_search_rightmost(val: series int/float) -> series int
array.binary_search_rightmost(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 larger 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 last match, or of the nearest higher item.

Example

Pine ScriptInsertion point in a sorted listOpen in editor
//@version=6
indicator("array.binary_search_rightmost: slot", overlay = false)
var levels = array.from(10.0, 20.0, 20.0, 30.0)
plot(array.binary_search_rightmost(levels, 20.0), "Value present")
plot(array.binary_search_rightmost(levels, 25.0), "Value absent")

See also

Runs on Sidechair