Search code examples
javascriptarrayschunkssplice

Split an Array with specific chunks size


For example I have a chunks array, this array has the sizes of individual chunks.

let example = [3,3]; // Chunks array
let auxarrayindex = [1,2,3,4,5,6]; // Array that I want to splice
let example2 = [3,2,3]; // Chunks array
let auxarrayindex2 = [1,2,3,4,5,6,7,8]; // Array that I want to splice

The result that I want is:

[1,2,3],[4,5,6] and the second [1,2,3],[4,5],[6,7,8]

This is my code:

for (let auxexample = 0; auxexample < example.length; auxexample++) {
    finalauxarray.push(auxarrayindex.slice(0, example[auxexample]));
}

The result from my code is:

[1,2,3],[1,2,3] and the second [1,2,3],[1,2],[1,2,3]

Solution

  • The problem is that your slice always starts at the same index (0).

    Use a variable (like i) that you increase as you take chunks:

    let example = [3,2,3];
    let auxarrayindex = [1,2,3,4,5,6,7,8];
    
    let finalauxarray = [];
    let i = 0;
    for (let auxexample = 0; auxexample < example.length; auxexample++) {
       finalauxarray.push(auxarrayindex.slice(i, i+=example[auxexample]));
    }
    
    console.log(finalauxarray);

    You could also use map for your loop:

    let example = [3,2,3];
    let auxarrayindex = [1,2,3,4,5,6,7,8];
    
    let i = 0;
    let finalauxarray = example.map(size => auxarrayindex.slice(i, i+=size));
    
    console.log(finalauxarray);