# Filter range "in place" explanation

This is the solution of exercise from another website I am using.

``````function filterRangeInPlace(arr, a, b) {

for (let i = 0; i < arr.length; i++) {
let val = arr[i];

// remove if outside of the interval
if (val < a || val > b) {
arr.splice(i, 1);
i--;
}
}

}

let arr = [5, 3, 8, 1];

filterRangeInPlace(arr, 1, 4);

``````

Why do we need ‘i–’ here? I see that it doesn’t work properly without it, but what is going on under the hood? Could someone explain please?

This is the task btw: Write a function `filterRangeInPlace(arr, a, b)` that gets an array `arr` and removes from it all values except those that are between `a` and `b` . The test is: `a ≤ arr[i] ≤ b` . The function should only modify the array. It should not return anything.

Hi @Ivan999. You need `i--` because you are looping through the `arr` array at the same time mutating it (modifying it) . If for example `i` is equal to `1` when the `if` condition evaluates to `true`, you will remove the element at index `1`. The element which should have been at index `i + 1` which is index `2`will be shifted to index `i` which is index `1` because of removing the element before it. But the problem is that the code inside the loop will be executed next when the value of `i` is `2` but the element which should have been in index `2` is now in index 1. So `i--` will reduce `i` from `1` to `0` so that the `i++` will take it back to `1` and executing the loop again for `i = 1` to cater for the new element at index `1`. If you don’t do `i--`, you are bound to skip executing the loop for the new element which has been shifted to index `1`. `i--` reduces the value of `i` by 1.

1 Like

The for loop runs as long as `i < arr.length`, but the `splice` method changes the length of the array, because it removes 1 item. If you wouldn’t decrease `i` by 1, the loop would run longer than it should. It would run into a situation where it tries to assign `let val = arr[i]`, but there is no item in the array at that index anymore.

1 Like

Thanks guys, I think I understand now…

1 Like