Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda