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>
CodePudding user response:
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(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 itemIndex = 1, length = 5, remove first remaining itemIndex = 2, length = 4, remove first remaining itemIndex = 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(index = fruits.length-1; index >= 0; --index) {
if(fruits[index] === 'Banana') {
fruits.splice(index, 1);
}
}
CodePudding user response:
.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 .pop().
const fruits = ["Banana", "Banana", "Banana", "Banana", "Banana", "Banana"];
for (let i = fruits.length; i >= 0; i--) {
if (fruits[i] === "Banana") {
fruits.pop();
}
}
console.log(fruits);
<div ></div>
