Skip to content

Instantly share code, notes, and snippets.

@webinista
Last active March 29, 2023 23:02
Show Gist options
  • Select an option

  • Save webinista/11240585 to your computer and use it in GitHub Desktop.

Select an option

Save webinista/11240585 to your computer and use it in GitHub Desktop.
Array.prototype.chunk: Splits an array into an array of smaller arrays containing `groupsize` members
/*
Split an array into chunks and return an array
of these chunks.
With kudos to github.com/JudeQuintana
This is an update example for code I originally wrote 5+ years ago before
JavaScript took over the world.
Extending native objects like this is now considered a bad practice, so use
the stuff between the curly braces and create your own function instead.
*/
Array.prototype.chunk = function(groupsize){
var sets = [], chunks, i = 0;
chunks = Math.ceil(this.length / groupsize);
while(i < chunks){
sets[i] = this.splice(0, groupsize);
i++;
}
return sets;
};
@JudeQuintana
Copy link
Copy Markdown

Thank you for this. How about a non destructive chunk method as to preserve the current array?

Array.prototype.chunk = function (groupsize) {
var sets = [];
var chunks = this.length / groupsize;

for (var i = 0, j = 0; i < chunks; i++, j += groupsize) {
  sets[i] = this.slice(j, j + groupsize);
}

return sets;

};

@jahan-addison
Copy link
Copy Markdown

jahan-addison commented May 19, 2016

Another way: const foldm = (r,j) => r.reduce((a,b,i,g) => !(i % j) ? a.concat([g.slice(i,i+j)]) : a, []);
r is the array, j the group size

@augnustin
Copy link
Copy Markdown

👍 for the ES6 version though I don't understand why using useless variable names despite being a 1-liner.

@chadbr
Copy link
Copy Markdown

chadbr commented Feb 26, 2018

In Typescript:

  public static chunk<T>(arr: Array<T>, chunkSize: number): Array<Array<T>> {
    return arr.reduce((prevVal: any, currVal: any, currIndx: number, array: Array<T>) =>
      !(currIndx % chunkSize) ?
      prevVal.concat([array.slice(currIndx, currIndx + chunkSize)]) :
      prevVal, []);
  }

@jerrylau91
Copy link
Copy Markdown

the reduce is perfect!

@christophemarois
Copy link
Copy Markdown

My take on it:

function chunk (arr, size) {
  return arr.reduce((chunks, el, i) => {
    if (i % size === 0) {
      chunks.push([el])
    } else {
      chunks[chunks.length - 1].push(el)
    }
    return chunks
  }, [])
}

@AndresSepar
Copy link
Copy Markdown

AndresSepar commented Oct 20, 2018

This is a variant that preserves the original Array Demo

Array.prototype.chunk = function (chunk_size) {
  var temp = this.slice(0),
      results = [];
    
  while (temp.length) {
    results.push(temp.splice(0, chunk_size));
  }
  return results;
};

var arr = [1,2,3,4,5,6,7];

console.log(arr.chunk(3), arr);

@mattshardman
Copy link
Copy Markdown

Using currying, to allow partial application:

const chunkArray = chunkSize => array => {
    return array.reduce((acc, each, index, src) => {
        if (!(index % chunkSize)) { 
            return [...acc, src.slice(index, index + chunkSize)];
        } 
        return acc;
        },
    []);
}

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

const chunkArray3 = chunkArray(3);
const chunkArray5 = chunkArray(5);
chunkArray3(array);
// => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]];
chunkArray5(array);
// => [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]];

@tpoisseau
Copy link
Copy Markdown

Here is mine, with generators approch. usefull when you want deal with bunch of data but keep small memory usage. And you can imagine handle an unlimited data flow with it ^^.

function* ennumerate(iterable, offset=0) {
  let i = offset;

  for (const item of iterable) {
    yield [i++, item];
  }
}

function* chunkor(iterable, size) {
  let chunk = [];

  for (const [index, item] of ennumerate(iterable, 1)) {
    chunk.push(item);

    if (index % size === 0) {
      yield chunk;
      chunk = [];
    }
  }

  if (chunk.length > 0) yield chunk;
}

/*
> [...chunkor([0,1,2,3,4,6,7,8,9], 2)]
[ [ 0, 1 ], [ 2, 3 ], [ 4, 6 ], [ 7, 8 ], [ 9 ] ]
> [...chunkor([0,1,2,3,4,6,7,8,9], 3)]
[ [ 0, 1, 2 ], [ 3, 4, 6 ], [ 7, 8, 9 ] ]
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment