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

103
Vistas
Split array into a chunk and then remove the chunk from the original array

This is the type of data I have:

["2", "Something1", "Something2", "4", "Something3", "Something4", "Something5", "Something6", "2", "Something7", "Something8"]

The number indicates how big the chunk should be.

const splitInput = (input: string[]) => {
  const chunks: string[][] = [];

  input.forEach((element) => {
    if (element.length === 1) {
      const chunk = input.splice(input.indexOf(element) + 1, parseInt(element));
      console.log(chunk);
      chunks.push(chunk)
    }
  });

The code above works only until there's no same numbers, since indexOf finds the first occurence. How can I either calculate fromIndex of indexOf() properly or remove all the removed elements from the array (including the numbers)?

This would be the expected output

[ ["Something1", "Something2"], ["Something3","Something4","Something5","Something6"],["Something7", "Something8"] ]

Before anyone asks, yes this is a part (not the whole thing, this is just a beginning, I'm going to have to do something with the chunks) of my homework. I have been trying everything for the past 2 hours and couldn't figure it out.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I don't know how to fix your approach but another approach is to iterate over the chunk sizes and fill another array with the chunks:

function splitInput(elements) {
    const result = [];
    for (let i = 0, end = elements.length; i < end; i += 1 + +elements[i]) {
        result.push(elements.slice(i + 1, i + 1 + +elements[i]));
    }
    return result;
}

const elements = ["2", "Something1", "Something2", "4", "Something3", "Something4", "Something5", "Something6", "2", "Something7", "Something8"];

console.log(splitInput(elements));

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