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

144
Visualizações
Reduce method of array not reaching last element

So I'm really new to JavaScript, and I'm having a bit trouble with reduce method in JavaScript which doesn't reach the last element of the array. My function removes duplicates from array by first sorting the array, and then using the reduce method to delete element if first and second element are same.

I'm thinking maybe it has something to do with the splice method I use in conjunction with it. But I'm not entirely sure what is going on, can someone help explain what's happening here?

function removeduplicate3(arr) {
  arr.sort((first, second) => (first > second));
  console.log(arr);
  arr.reduce((first, second) => {
    console.log(`${first} ${second}`); // check pair of elements it reduces
    if (first === second) {
      arr.splice(arr.indexOf(second), 1)
      return first;
    } else
      return second;
  }, undefined);
}

let arr = ["Hello", "World", "Bye", "World", "I", "Am", "I", "World"];

console.log(removeduplicate3(arr));

my finally (incorrectly) filtered array has: [ "Am", "Bye", "Hello", "I", "World", "World" ]

I printed the pairs of elements of array with ${first} ${second}, and it's missing the last pair: World World

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