mardi 11 juin 2019

Why if statements blocks in while loop?

I have an array of numbers with a bunch of duplicates. I need to get rid of them so I put the code:

  let dup = arr.filter((elem, pos)=> arr.indexOf(elem) !== pos);
  // dup Array contains the duplicate numbers
  arr = arr.filter((elem, pos)=> arr.indexOf(elem) == pos);
  //arr contains the whole array with duplicates
  let i = 0;
  let j = 0;
  while(i<arr.length){
    while(j<dup.length){
      if(arr[i] == dup[j]){
        arr.splice(i, 1);
        //the splice method resets the decrease the index of the array so
        i--;
      };
      j++;
    };
    i++
  }

The problem is that the if doesn't run after the first match.So the array splice the first duplicate that it finds and stops. How can I fix that?

Aucun commentaire:

Enregistrer un commentaire