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

203
Visualizações
How to group all contiguous even numbers into a 2D array?

I've the following array of numbers:

[10, 12, 23, 17, 14, 15, 50, 72, 26, 33]

And I want to group all even numbers that appear together, as below:

[ [ 10, 12 ], [ 14 ], [ 50, 72, 26 ] ]

I'm able to filter out the even numbers, but I'm unable to group the contiguous ones together. I think reduce can be used here, but I'm unable to understand how, any help is highly appreciated.

const nums = [10, 12, 23, 17, 14, 15, 50, 72, 26, 33];
const result = nums.map((n, i) => (n % 2 === 0 ? [n] : []));

console.log(result);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use Array.prototype.reduce

For every number that is even, do the following:

  1. Push an empty array into the resultant array if the last number was not even (i.e. it was odd).

  2. Get the last group in the resultant array using Array.prototype.at and then push the current number into this group.

const 
  nums = [10, 12, 23, 17, 14, 15, 50, 72, 26, 33],
  result = nums.reduce((res, num, i) => {
    if (!(num & 1)) {
      if (!i || nums[i - 1] & 1) {
        res.push([]);
      }
      res.at(-1).push(num);
    }
    return res;
  }, []);

console.log(result);

Note: I've used the Bitwise AND (&) operator to check if a number is even or odd, you could also use the Remainder operator (%).

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