I want to remove the elements of an array with n elements using a for loop and the splice method one by one. The loop is executed n - 2 times and there will be 2 elements inside the array at the end. Why is that so?
const fruits = ['Apple', 'Orange', 'Watermelon', 'Peach']
for(index in fruits){
console.log('Execution Number:', index);
console.log('Before:', fruits);
fruits.splice(0, 1);
console.log('After:', fruits);
console.log('-'.repeat(50));
}
console.log('\nFinal Result:', fruits)
result:
Execution Number: 0
Before: [ 'Apple', 'Orange', 'Watermelon', 'Peach' ]
After: [ 'Orange', 'Watermelon', 'Peach' ]
--------------------------------------------------
Execution Number: 1
Before: [ 'Orange', 'Watermelon', 'Peach' ]
After: [ 'Watermelon', 'Peach' ]
--------------------------------------------------
Final Result: [ 'Watermelon', 'Peach' ]
I know that I can do this with a single line of code using the splice method but I wanted to test if I can do this using a for loop.