Below function works nice
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--;
}
}
}
arr=[2,3,4,5,6,7,1,0,2,12,11];
filterRangeInPlace(arr,1,5);
alert(arr);
but I want to do the same function with the forEach
let filterRange = (arr, a, b) => {
arr.forEach((item, i) => {
val=item;debugger;
if (val < a || val > b) {
arr.splice(i, 1);
i--;
}
})
}
arr=[2,3,4,5,6,7,1,0,2,12,11];
filterRange(arr,1,5);
alert(arr);
I tried it, but I could not get the right answer. It doesn't work as normal iterations. is there any another way of using the same foreach