Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda