Home  >  Q&A  >  body text

javascript - What does j-- in the second for loop mean?

var arr = [ 1,2,2,4,2 ];

for ( var i=0; i<arr.length; i++ ) {

for ( var j=i+1; j<arr.length; j++ ) {
    if ( arr[i] == arr[j] ) {
        arr.splice( j, 1 );
        j--;
    }
}

}

三叔三叔2668 days ago1741

reply all(2)I'll reply

  • 某草草

    某草草2017-06-30 10:00:48

    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.

    reply
    0
  • 代言

    代言2017-06-30 10:00:48

    What you said above is correct. To add, it can be achieved directly by using filter.

    var arr = [ 1,2,2,4,2 ];
    
    arr.filter(function (e, i) {
        return arr.indexOf(e) === i;
    })

    reply
    0
  • Cancelreply