I need to write a function
filterRangeInPlace(arr, a, b)
that takes an array and two numbers and deletes all elements from the array that are not within the range a to b. So the check looks like
a ≤ arr[i] ≤ b
I want to do it with the for loop and splice method. But can't figure out why the function keeps some elements outside of the range, in my case below it's number 3. This is not a home task or whatever, I'm just practicing array methods. Here's my code:
let myArr = [1, 3, 8, 3, 9, 5, 3, 4, 10, 7, 6, 1]
function filterRangeInPlace( arr, a, b ) {
for ( i = 0; i < arr.length; i++ ) {
if ( arr[i] < a || arr[i] > b ) {
arr.splice(i, 1)
}
}
}
filterRangeInPlace(myArr, 4, 9)
console.log(myArr) // [3, 8, 9, 5, 4, 7, 6]
I understand I messed with the index somewhere, but can't figure out where and how, as the rest works fine. Thanks!