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

66
Views
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 answers
Answer question

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