Finding the index of the last element that gets repeated consecutively (Javascript)

52 Views Asked by At

PROBLEM I'm working on a codewars problem where I'm supposed to find the peaks of an array. For example, [4, 9, 3, 2, 1] => 9 would be considered a peak because the values before and after it are lower than it.

I've been able to identify the peak by simply writing a for loop and an if statement where if (a[i] > a[i+1] && a[i] < a[i-1]) return a[i]

In some instances, peak/plateaus can happen when the highest number is repeated. For instance [3, 6, 9, 9, 9, 9, 7]. Since the plateaus length can vary to any degree, I want to figure out the index for when the 9 stops repeating (index stop = 5) or even when the new value starts (7).

ATTEMPTS I wanted to try to use a for loop, but it seems like I can only use it for values that come immediately after one another. I tried looking into the .repeat function, but it seems to only create and not identify the index of existing repetitions. New Set will show me the unique values, but it will alter the original array.

I'm not sure how I would implement .length.

.lastIndexOf won't work either because I don't want my function to pick up values that are the same as the peak but are located later in the array. For example [3,4,9,9,9,2,9,10,8] => The first 9 would be a peak, but the last nine would not.

I don't want to mutate the array by taking out existing values from it because I'm supposed to return the indexes of peak. Mutating it will change the index. Non-regex methods would be preferable!

I'd appreciate any input! Thanks!

0

There are 0 best solutions below