Reputation: 151
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>
Upvotes: 0
Views: 103
Reputation: 43910
.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);
Upvotes: 1
Reputation: 45252
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>
Upvotes: 1