Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda