Delete Array Elements while Iterating Array in Javascript

·   ·  ☕ 2 min read

Removing array elements while iterating through the elements in a loop can be tricky for a beginner.

Consider this -

 1 2 3 4 5 6 const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (let i = 0; i < nums.length; i++) { console.log(nums[i]); nums.splice(i, 1); }

This looks like a lazy weekend programming puzzle, but also goes to demonstrate what can happen if the loop is not understood well.

The above code does not delete all elements but removes alternate elements.

 1 2 console.log(nums); // [ 2, 4, 6, 8, 10 ]

In the for loop splice removes one element each time. When we step through time -

Iteration nums Index (i) postn. Element at nums[i] Array after delete
1 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 0 1 [2, 3, 4, 5, 6, 7, 8, 9, 10]
2 [2, 3, 4, 5, 6, 7, 8, 9, 10] 1 3 [2, 4, 5, 6, 7, 8, 9, 10]
3 [2, 4, 5, 6, 7, 8, 9, 10] 2 5 [2, 4, 6, 7, 8, 9, 10]
4 [2, 4, 6, 7, 8, 9, 10] 3 7 [2, 4, 6, 8, 9, 10]
5 [2, 4, 6, 8, 9, 10] 4 9 [2, 4, 6, 8, 10]

As you see, we processed the array in half as many steps as we anticipated at the beginning. This is because each time the array shrank with splice but i continued to increment and delete the element at ith position. So, every alternate elements got deleted.

Avoiding the problem is easy. You just increment your own counter, or go reverse while iterating the array.

 1 2 3 4 5 6 7 const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (let i = nums.length - 1; i >= 0; i--) { console.log(nums[i]); nums.splice(i, 1); } console.log(nums); // [ ]
Stay in touch!
Share on

WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things