0

Currently I'm making my way through TOP. I am on the removeFromArray problem, and I'm running into one issue I can't figure out.

When I input:

removeFromArray([1, 2, 3, 4], 2, 3);

the function returns [1, 4], as it should, but when I reverse that to

   removeFromArray([1, 2, 3, 4], 3, 2);

the function returns [1, 3, 4]

Compared to the solution TOP has listed, it's definitely not optimized, but I'd love to learn why this method isn't working before moving on. Here is the code for the function.

const removeFromArray = function(array, ...args) {

for (let i = 0; i < array.length; i ++) {
    for (let j = 0; j < args.length ; j++){
        if (array[i] === args[j]) {
            array.splice(i, 1);
    }
   
    }
    
}
return array;
};
  • the function working as it written, you have some logical issue. In second case when 'splice' removes '2' from your array, the array.length == 3 and i == 2. So in next loop array[i] == 4 and it will not splice number '3' from array. – Tatul Mkrtchyan Jul 07 '22 at 19:31
  • 1
    Ahh. I gotcha. That helps a ton. I instead decremented i by 1 after the splice and that seemed to fix it. Thanks for the help man! – RockyRoads Jul 08 '22 at 23:54

1 Answers1

0
const removeFromArray = function(array, ...args) {
for(let i = 0 ;i< args.length  ; i++){
    array = array.filter((ele)=>ele!==args[i]) 
}
return array;
};
Adem_Bc
  • 48
  • 6
  • Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. – Saeed Zhiany Jul 08 '22 at 07:16