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

221
Visualizações
Javascript check if numbers in an array are consecutive and store them?

I have an array like this:

arr = [1,3,4,5,7,8]

I need to check if the next number is consecutive to the current number and, if it is, store both together otherwise i store the single number in an array.

The above array should give the following result:

newArray = [1, 345, 78]

I tried a simple solution and only achieve what i wanted if was only 2 consecutive numbers:

for (i = 0; i < array.length; i++) {
    if (array[i] === array[i - 1] + 1) {
        newArray.push(array[i - 1] + array[i]);
    } else {
        newArray.push(array[i]);
    }
}

And when i tried to do for more numbers things got very messy.

I know this doesnt look like a major problem, but i am trying this for hours and cant find the result.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can do something like this

const arr = [1,3,4,5,7,8]

const groupConsecutive = arr => {
 const result = arr.reduce((res, n) => {
  if(n - res.prev === 1){
    return {
      prev: n,
      current: [...res.current, n.toString()],
      total: res.total
    }
  }
  return {
    prev: n,
    current: [n.toString()],
    total: [...res.total, res.current]
  }

}, {prev: '', current: [], total: []})
 return [...result.total, result.current].flatMap(n => Number(n.join('')))
}

console.log(groupConsecutive(arr))

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