Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
how to remove following arguments after the array

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));

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report

0

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));

about 4 years ago · Juan Pablo Isaza Report

0

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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!