So consider this: you’re incrementing over the array, and you have this loop variable you’ve defined (you’re calling it i). Inside your loop, do you want to refer to arr[0], or arr[i]? So, for example,
if(func(arr[i]) === true){
// what do you want to do here?
}
And then, if it’s NOT true, you simply jump to the next iteration of the loop. Then you just need to figure how you’ll handle the case of NO matches.
im using arr[0] on purpose becasue every time i’m removing the first element of the array that doesn’t match the condition so i’m always staying at arr[0]
It isn’t the best of ideas to mutate arrays as you are looping over them like that. Picture a woody woodpecker cartoon, where he’s sawing a tree limb while standing on it.
Here’s a pseudocode version of the cleanest, easiest-to-understand way to handle this:
for (loop over every element of array, using an index){
if (running func with array[index] is true) {
return the sliced array from that index to the end
}
} End the for loop
If we get here, then we had no true elements, return an empty array
Note that that isn’t the only solution, simply the cleanest. What you’re doing is potentially mutating that array each iteration, leaving the original array in an unpredictable state.
The reason you’re getting unexpected results is, you keep incrementing i, and comparing it at each iteration to the length of arr… which is now changing. So say, at the third iteration, my array has been reduced to two members that I still need to compare, but i is now at 3, thus exceeding my array length. The loop stops.
For this logic to work, you’ll need to define a variable before the loop happens, like this: