Search code examples
javascriptarraysforeachsplice

Why can't I remove elements from the array?


This function should remove elements that are less than 1 and more than 4, but it doesn't. The array is still the same.

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

function filterRangeInPlace(arr, a, b) {
    arr.forEach((item, index) => {
        if (a > item && b < item) {
            arr.splice(index, 1);
        };
    });
};

filterRangeInPlace(arr, 1, 4);
console.log(arr);

What's wrong?


Solution

  • When would an individual item be both less than 1 and more than 4? If you want to remove items that are less than 1 or more than 4 you need to do:

    if (a > item || b < item)