2

I am trying to remove duplicates from an array but am getting two extra number "2". It works fine when I replace the element with 0. It gives an error only when I pop() the element.

For this input [0,0,1,1,1,2,2,3,3,4] I would expect [0,1,2,3,4]. Why are there two extra 2s when using pop()?

function removeDuplicate(arr) {
  var i = 0;
  var j = 1;
  while (j < arr.length) {
    if (arr[i] === arr[j]) {
      j++;
    } else {
      arr[++i] = arr[j];
      j++;
    }
  }
  for (i = i + 1; i < arr.length; i++) {
    // arr[i] = 0;
    arr.pop();
  }

  return arr;
}

const ans = removeDuplicate([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])
console.log(ans);
Ankit Kumar
  • 218
  • 2
  • 13
  • 1
    Your question is what's wrong with **your** code, right? Not other ways to solve the problem? If so, I'd make that cllearer in both the title and text. Right now, this is a duplicate of at least a dozen other questions that have answers. – T.J. Crowder Dec 17 '21 at 10:19
  • 1
    If you're looking for a code review, you should move your question to https://codereview.stackexchange.com, they'll point out all mistakes, and what can be improved in your code. If you're just looking on how to remove duplicates, there are many answers already on SO – Youri Dec 17 '21 at 10:22
  • Does this help you? https://www.javascripttutorial.net/array/javascript-remove-duplicates-from-array/ – Dequog Dec 17 '21 at 10:25
  • 1
    No, I am asking why I am getting the wrong answer on pop(). Please tell only that. This question I got asked in the Interview and I was got rejected because of this. – Ankit Kumar Dec 17 '21 at 10:28

2 Answers2

0

For Loop Should be like this in order to get correct output:

for(let k = arr.length; k > i+1; k--){
        arr.pop()
    }
Ankit Kumar
  • 218
  • 2
  • 13
  • your for loop in the question works either. All you have to do is simply store the `arr.length` in a variable rather than using directly in the for loop's condition :) – Deepak Dec 17 '21 at 11:06
  • You could also do the following `while (arr.length > i+1) { arr.pop(); }` – Sandsten Dec 17 '21 at 11:06
0

Solution:

function removeDuplicate(arr) {
    var i = 0;
    var j = 1;
    while (j < arr.length) {
      if (arr[i] === arr[j]) {
        j++;
      } else {
        arr[++i] = arr[j];
        j++;
      }
    }
    for(let k = arr.length; k > i+1; k--){
        arr.pop()
    }
  
    return arr;
  }
  
  const ans = removeDuplicate([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])
  console.log(ans);
Ankit Kumar
  • 218
  • 2
  • 13