Home > Software design >  how to remove following arguments after the array
how to remove following arguments after the array

Time:06-29

destroyer(array1, some arguments) function should return the array1 excluding the arguments. I found some working ways like return arr = arr.filter(val => !rem.includes(val)); but I need to fix this code and find out why this code giving an incorrect result. It supposed to be [1]

function destroyer(arr, ...rem) {  
  for(let i = 0; i < arr.length; i  ) {      
      if (rem.includes(arr[i])) {
        arr.splice(i, 1);
      };    
  };
  return arr;  
}

console.log(destroyer([3, 5, 1, 2, 2], 2, 3, 5));

CodePudding user response:

function destroyer(arr, ...rem) {  
const itemsToRemove = new Set(rem);
  return arr.reduce((acc, curr) => itemsToRemove.has(curr) ?  acc : [...acc, curr] ,[])
}

console.log(destroyer([3, 5, 1, 2, 2], 2, 3, 5));

CodePudding user response:

Or you can do it like this:

const destroyer=(arr, ...rem)=>arr.filter(v=>!rem.includes(v));

console.log(destroyer([3, 5, 1, 2, 2], 2, 3, 5));

CodePudding user response:

The problem is the call of the function Array.prototype.splice within the for loop, this function is mutating the array and basically affects the indexes of the array, therefore the current index i is no longer valid.

To work around this, you can loop in a backward direction, this way we can mutate the array, and the current index is not affected.

One more thing, your approach is mutating the array, a better approach would be by using the function Array.prototype.filter along with the function Array.prototype.includes, see other answers.

function destroyer(arr, ...rem) {
  for(let i = arr.length; i >= 0; i--) {      
      if (rem.includes(arr[i])) {
        arr.splice(i, 1);
      };    
  };
  return arr;  
}

console.log(destroyer([3, 5, 1, 2, 2], 2, 3, 5));

  • Related