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

160
Visualizações
How can I find & groups pairs from an array while changing the original array?

So for ex. I have this array with these values :

let arr = [1, 2, 3, 3, 3, 4, 4];

How can I get a new arr as :

let newArr = [3, 3, 4, 4];

while at the same time the original array should be changed as :

let arr = [1, 2, 3];

one 3 is left behind cause there is only one pair of 3.

I tried this code below ( a for loop & splice ) but it is not working properly.

let result = [];

for (let i = 0; i < sorted.length; i++) {
    if (sorted[i] === sorted[i + 1]) {
        let pair = sorted.splice(i, 1);
        pair.forEach(el => result.push(el));
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Few things corrected,

  1. You need to splice two items from the point you see duplicates. Try like this.
  2. Iteration stop condition should be i < sorted.length - 1 as we consider two consecutive items.
  3. Use Array.prototype.concat to join duplicates to the result array.

let sorted = [1, 2, 3, 3, 3, 4, 4];
let result = [];

for (let i = 0; i < sorted.length - 1; i++) {
    if (sorted[i] === sorted[i + 1]) {
        let pair = sorted.splice(i, 2);
        result = result.concat(pair);
        i--;
    }
}

console.log(sorted)
console.log(result)

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