If duplicates are encountered, splice them out of arr. After splice is removed, the next item in the array is still the current index, so you need to first j--; and then j++ in the loop to keep the index correct.
For example, in the second outer loop, i = 1, j = 2, then arr[1] is 2, arr[2] is also 2, arr[2] will be splice out, and the array becomes [1,2, 4,2], the next element 4 is still the 2nd item, and will be missed if j-- is not done first.
If duplicates are encountered, splice them out of arr. After
splice is removed, the next item in the array is still the current index, so you need to first
j--
; and thenj++
in the loop to keep the index correct.For example, in the second outer loop, i = 1, j = 2, then arr[1] is 2, arr[2] is also 2, arr[2] will be splice out, and the array becomes [1,2, 4,2], the next element 4 is still the 2nd item, and will be missed if
j--
is not done first.What you said above is correct. To add, it can be achieved directly by using
filter
.