Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!