Search code examples
javascriptarrayschunking

Array chunking - Possible in one Array?


Lets say i have this

    var array =[23,345,6,765,54423,45654,7657,43,43,5,765,3456,768,897,545,645,87,4556,432,543,534];
var chunkEachBy = [3,2,1,5,6,4];

var chunked = [];


for(var i =0, l = chunkEachBy.length; i < l; i++)
{
     chunked.push(array.splice(0, chunkEachBy[i]));   
}

output:

[Array[3], Array[2], Array[1], Array[5], Array[6], Array[4]]

which simply chunks array into the length of the chunkEachBy, then chunk each value for each chunkEachBy.

My question is, instead of pushing the result of this into a seperate array in this case named chunked can this all be done to the original array and produce the same result?

JSFiddle - https://jsfiddle.net/b7twnurm/1/


Solution

  • Use a double splice with i as index:

    array.splice(i, 0, array.splice(i, chunkEachBy[i]));
    

    Explanation:

    i points to the first element of the array that we have not yet processed, or after the last element we added.
    The splice taking two arguments (array.splice(i, chunkEachBy[i])) removes a number of elements from array from position i, and the one taking three arguments inserts them all back to the position they were just taken from, but now as an array (because that's what array.splice returns).

    Also see the array.splice documentation for the third parameter.

    Updated fiddle: https://jsfiddle.net/b7twnurm/2/