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);