Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
Removing duplicates from an array leaves duplicate values in the end result

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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);
about 4 years ago · Juan Pablo Isaza Report

0

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

for(let k = arr.length; k > i+1; k--){
        arr.pop()
    }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!