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

102
Visualizações
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 Respostas
Responde à pergunta

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 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