1. forEach Loop ==========
Example: Removing elements equal to 1 from an array during iteration.
let arr = [1, 1, 2];
arr.forEach((item, index, array) => {
if (item === 1) {
array.splice(index, 1);
}
});
console.log(arr); // Output: [1, 2]
Result: After iteration, the output is [1, 2], leaving one instance of 1 untouched.
Cause Analysis:
- First iteration: Array is
[1, 1, 2], index is 0, item is 1. Condition matches, sospliceremoves it, resulting in[1, 2]. - Second iteration: Array is now
[1, 2], index is 1, item is 2. Condition does not match, no removal occurs.
The issue arises because modifying the array during forEach disrupts element indexing.
Solution: Use filter() to create a new array excluding unwanted items.
// Example 1: Filtering out elements with value 1
let arr = [1, 1, 2];
arr = arr.filter(item => item !== 1);
console.log(arr); // Output: [2]
// Example 2: Filtering objects based on property value
let products = [
{ id: 1, name: 'TV', stock: 20 },
{ id: 2, name: 'Washer', stock: 0 },
{ id: 3, name: 'Refrigerator', stock: 50 },
{ id: 4, name: 'AC', stock: 0 }
];
products = products.filter(product => product.stock !== 0);
console.log(products);
2. for and for...in Loops ===================
/**
* Correct approach - Adjusting index during traversal
*/
for (var i = 0; i < arr.length; i++) {
if (/* condition */) {
arr.splice(i, 1); // Shifts remaining elements left, reduces length
i--; // Compensates for shift to avoid skipping elements
}
}
/**
* Incorrect approach - for...in does not ensure sequential traversal
*/
for (var i in arr) {
if (/* condition */) {
arr.splice(i, 1); // Shifts remaining elements left, reduces length
i--; // Has no effect, still skips elements
}
}