Search code examples
javascriptlogic

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.


Solution

  • 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));