Remove from array multiple times

this code doesn’t work with spread syntax, but without spread syntax it works and remove first argument “3” , can anyone help what’s the problem?

const removeFromArray = function (array, ...deleteElement) {
    for (let i = 0; i < array.length; i++) {
        if (array[i] === deleteElement) {
            array.splice(i, 1);
        }
    }
    return array;
};

const arrayOne = [1, 2, 3, 4, 5, 6, 7, 8, 9];
removeFromArray(arrayOne, 3, 5)

array[i] === deleteElement

You are comparing an integer in an array with a whole array. The result will always be False.

It is a rest parameter. It will be an array no matter how many arguments are collected.

function test(one, ...rest) {
  console.log(one); // 1
  console.log(rest); // [2, 3, 4, 5]
}

test(1, 2, 3, 4, 5);

Also, you are mutating the array which isn’t a good idea. I would suggest using filter and includes for this.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.