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

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

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