Home > Net >  Why can't I remove elements from the array?
Why can't I remove elements from the array?

Time:10-09

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?

CodePudding user response:

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)

CodePudding user response:

you are inverting the arguments when calling the function. you should rather do

filterRangeInPlace(arr, 4, 1)

CodePudding user response:

you are basically keeping items between given range instead removing items go for keeping items this will return same also use filter function it basically iterate through array and just like foreach there are two parameters inside it item and index the only difference is filter keeps value when you return true or ignore if you return false

you can check more about filter here filter

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

function filterRangeInPlace(arr, a, b) {
    return arr.filter(each=>{
       return each > a && each < b
    })
};

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

  • Related