Best way to find first occurence in an array

Using the ValueWhen it is very easy to find the LAST element of an array, when a condition is met.

I want to find the FIRST element of an array, when a condition is met.

One idea is to use the SparseCompress, sort all special points of the array to the end, and then use a loop to go to the first one.

Is there a better way to do it?

For example I want to find the Barindex() of the first Peak, using ZIG.

I assume you already know how to find the peaks. If so, the logic for identifying the first one is straightforward:

isPeak = // Your logic here
countPeaks = Cum(isPeak);
firstPeakBar = ValueWhen(countPeaks == 1, BarIndex());

If you did not in fact want to look at the ENTIRE array (which would typically be the case), you could use SumSince() instead of Cum() to start the counting from some other event, for example the first bar that's in range.


Hi mradtke

Thank you very much for the idea (to use CUM(isPeak)). Here is the tested code that works:

countPeaks = Cum(isPeak); 

firstPeakBar = ValueWhen(countPeaks == 1 AND ispeak, BarIndex());

lastPeakBar = ValueWhen(countPeaks == LastValue(countPeaks) AND ispeak, BarIndex());

Ah yes, sorry... I neglected the fact that countPeaks will continue to have a value of 1 until the second peak occurs. Good catch.