Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda