Search code examples
javascriptarrayssplicearray-splice

How would i create n no of chunks from an array of dynamic length javascript


I have an array of n length(dynamic) say 830... I want this array to be split in sub-array such in the manner [0,100],[100,200].....[800,829] i.e in equal no of chunks How would I execute this??

I have tried below code so far with reference of this answer

var i,j,chunk = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
    temparray = array.slice(i,i+chunk);
 }

But As described my array will be the dynamic i.e dynamic length if 380. and if no. of a chunk is 100 then have to return 80 at the end


Solution

  • You can try this

    function chunk(orig) {
      var n = Math.floor(orig.length / 100);
      var evenChunks = new Array(n).fill(0).reduce((agg, curr, index) => {
        agg.push(orig.splice(0, 100))
        return agg;
      }, []);
    
      return [].concat(evenChunks, [ orig ]);
    }
    

    You can then call like,

    chunk(new Array(830).fill(0))