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

217
Vistas
Split array into chunks of array if it is sequential in javaScript

I want to spilt array in chunks of array Input= [36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,57,58,59,60,61,62] Output= {[36,37,38,39],[40,41,42,43],[44,45,46,47],[48,49,50,51],[57,58,59,60]}

If there are no sequential numbers from 52 so it should not take that.
Can anyone help me out?
Thanks in advance.

I am currently using this code but in output it is not checking the sequence

    ```Array.prototype.chunk = function(n) {
      if (!this.length) {
        return [];
      }
      return [this.slice(0, n)].concat(this.slice(n).chunk(n));
    };
    console.log([36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72].chunk(4));    ```
This output is what i am currently getting but i want output as i mentioned above.
Output:

[
  [ 36, 37, 38, 39 ],
  [ 40, 41, 42, 43 ],
  [ 44, 45, 46, 47 ],
  [ 48, 49, 50, 51 ],
  [ 52, 57, 58, 59 ],
  [ 60, 61, 62, 63 ],
  [ 64, 65, 66, 67 ],
  [ 68, 69, 70, 71 ],
  [ 72 ]
]
      
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Not sure this is what you expected but you will get expected output in this way

console.log(chunk([36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72], 4));

function checkSequence(arr) {
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] - arr[i - 1] > 1) {
      return false;
    }
  }
  return true;
}
function chunk(arr, n) {
  let i = 0;
  var arr1 = [];
  while (i < arr.length) {
    const res = arr.slice(i, i + n);
    if (checkSequence(res) && res.length === 4) {
      arr1.push(res);
      i = i + n;
    } else {
      i = i + 1;
    }
  }
  return arr1;
}

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