Managing multiple splices in a loop can get confusing, as the position of each element changes after each splice operation. Here’s a little extension to help manage that:

The trick is in the call to sort() and the reduction of the index by the iteration count, which updates the originally passed index to match the new size and position of the array as modified by the previous iteration’s slice operation.

Usage is simple (i’ll use elements with the same value as its index for clarity, but is certainly not necessary)…



See also: removing multiple elements from an array