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

73
Views
splice() is not emptying the array

Below code should return empty array but it is returning Banana,Banana,Banana

const fruits = ["Banana", "Banana", "Banana", "Banana", "Banana", "Banana"];

fruits.map((ele) => {
  if (ele === "Banana") {
    fruits.splice(0, 1)
  }
})

document.getElementById("demo").innerHTML = fruits;
<div id="demo"></div>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This is actually doing what you're telling it.

An implementation of array.map could be like this:

array.prototype.map = function(transform) {
    let output = [];
    for(let index = 0; index < this.length; ++index) {
          output.push(transform(this[index]));
    }
    return output;
}

The loop would go like this:

  • Index = 0, length = 6, remove first item
  • Index = 1, length = 5, remove first remaining item
  • Index = 2, length = 4, remove first remaining item
  • Index = 3, length = 3, terminate loop

This is why it is only removing three items.

The upshot of this is that array.map is the inappropriate function for the job.

There's a number of ways you can implement this. One way is to iterate through the array backwards:

for(let index = fruits.length-1; index >= 0; --index) {
    if(fruits[index] === 'Banana') {
        fruits.splice(index, 1);
    }
}

An example:

const fruits = ["Banana", "Apple", "Banana", "Banana", "Orange", "Banana"];

for(let index = fruits.length-1; index >= 0; --index) {
    if(fruits[index] === 'Banana') {
        fruits.splice(index, 1);
    }
}

console.log(fruits);
<div class="demo"></div>

about 4 years ago · Juan Pablo Isaza Report

0

.forEach() goes in a forward direction (ex. 0...5) so if an element is removed then the length decreases as the length decreases to half to of the length, the index reference will be greater than the length -- hence half of the array remains.

When decreasing the length of an array, go in the revearse direcrtion (ex. 5...0). The example below uses a reverse for loop and .splice(i, 1).

const fruits = ["Banana", "Banana", "Banana", "Banana", "Banana", "Banana"];

for (let i = fruits.length; i >= 0; i--) {
  if (fruits[i] === "Banana") {
    fruits.splice(i, 1);
  }
}

console.log(fruits);

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!