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

68
Vistas
iterate throug array with removed elements by splice vs filter

Can somebody explain to me why the output is different? I remove one element in both cases so why does the for loop make a difference between splice and reasigning the value?

filter:
1 2 3 4 5

splice:
1 2 3 5

let arr = [];
let arr2 = [];

class test {
  constructor(s) {
    this.s = s;
  }

  destroy() {
    arr = arr.filter((e) => e !== this);
  }

  destroy2() {
    var index = arr2.indexOf(this);
    if (index !== -1) {
      arr2.splice(index, 1);
    }
  }
}

arr.push(new test("1"));
arr.push(new test("2"));
arr.push(new test("3"));
arr.push(new test("4"));
arr.push(new test("5"));

arr2.push(new test("1"));
arr2.push(new test("2"));
arr2.push(new test("3"));
arr2.push(new test("4"));
arr2.push(new test("5"));

console.log("filter: ");

for (let t of arr) {
  if (t.s === "3") {
    t.destroy();
  }
  console.log(t.s);
}

console.log("\nsplice: ");

for (let t of arr2) {
  if (t.s === "3") {
    t.destroy2();
  }
  console.log(t.s);
}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Please refer below piece of code.

Here the arr is part of the iterator, and you are changing the array within the for loop, but the iterator will be referring to memory location of arr.

But, you just assigned different location/memory to arr variable, but the iterator is still referring to old memory/location.

In case of splice, it modifies the contents of the memory, in case of filter it's just new object assignment.

for(let a of arr) {
    arr = arr.filter(i =>  i!=3); console.log(a); console.log(arr);
}
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