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

196
Vistas
Javascript Remove Duplicates Ints From Array

I'm working on a Leet code challenge where I'm trying to remove all duplicates from a sorted ascending array of integers.

So for example [1,1,1,2,2,3,4,5,5,5] should return [1,2,3,4,5].

I have solved this one way, but was trying a different way as per the code below, but it seems to always return an empty array [].

Could anyone point me in the direction (of what might be very obvious but I havent seen it) of why this always returns an empty array?

var removeDuplicates = function(nums) {
    
    for(let i = 0; i < nums.length; i++) {
        let counter = 0;
        for(let x = i + 1; x < nums.length; x++) {
            // Remove element if above is true
            if(nums[i] == nums[x]) {
                counter++;
            }
        }
        nums.splice(i + 1, counter);
    }
    return nums;
};

console.log(removeDuplicates( [1,1,1,2,2,3,4,5,5,5] ));

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You will get an empty array, because your algorithm is wrong. Your algorithm will works correctly just when the similar numbers are side by side each other. For example:

[1,1,1,2,2,5,5,5,5,5,3,3]

Otherwise it doesn't work correctly.

There are lots of algorithm to remove duplicated values from an array. Please have a simple search to find them. But you can easily remove duplicate values in an array in these ways:

function removeDuplicates(numbers) {
    return [...new Set(numbers)];
}

Or:

function removeDuplicates(numbers) {
    return numbers.filter((num, index, self) => index === self.indexOf(num));
}
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