Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda