Here, you modify the length of the array, which causes some elements to be skipped.
If you want to change the arr array in this way, you have to traverse its elements from end to beginning to avoid skipping elements. for (let i = arr.length - 1; i >= 0; --i) {
I understand. When you use splice() method, it modifies the array length, and you will not check the next element that goes after the current.
Look at the example:
let arr = ['a', 'b', 'c', 'd'];
for (let i = 0; i < arr.length; ++i) {
console.log(arr[i]) // this will output: a, b, d (no c here)
if (arr[i] === 'b' || arr[i] === 'c')
arr.splice(i, 1);
}
console.log(arr); // ['a', 'c', 'd']
sorry but I couldn’t understand properly. You are saying if I traverse the array from end to beginning then it will give me the correct output instead of beginning to end? I get this point that splice() method modifies the array length but it will modify in both the cases right?
Yes. It will modify in both the cases, but if you go from the end, you won’t skip elements.
Look at what happens when you delete an element.
let arr = [‘a’, ‘b’, ‘c’, ‘d’]
you deleted ‘b’ at index 1 and your array now
[‘a’, ‘c’, ‘d’] and “i” is 1, so on the next iteration “i” would be 2, and you will check value at index 2 that is ‘d’.
‘c’ will be skipped because the elements have been shifted to the left