I have an array in JavaScript which looks like this:
var myArray = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'];
I am interested in extracting elements from the array that come after two consecutive occurrences of a specific element.
For example, in the given array, I want to retrieve all elements that follow consecutive instances of 'x', 'x'
Therefore, the desired output would be:
'p'
'b'
Although I have found a solution to achieve this:
var arrLength = myArray.length;
for (var i = 0; i < arrLength; i++) {
if(i+2 < arrLength && myArray[i] == 'x' && myArray[i+1] == 'x') {
console.log(myArray[i+2]);
}
};
While this solution works, it is not very generic.
For instance, if I need to identify three consecutive occurrences, I would need to add another condition within the if statement for myArray[i+2] == 'x'
and so forth.
Is there a more efficient approach to fetching these elements?