Skip to content

Instantly share code, notes, and snippets.

@webinista
Last active March 29, 2023 23:02
Show Gist options
  • Save webinista/11240585 to your computer and use it in GitHub Desktop.
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;
};
@elin-y
Copy link

elin-y commented Sep 28, 2018

Here is my ES6 version, it has basically the same logic with the above version from @christophemarois:

const chunk = (arr, size) => arr.reduce((chunks, el, i) => (i % size 
    ? chunks[chunks.length - 1].push(el) 
    : chunks.push([el])) && chunks, [])

@AndresSepar
Copy link

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

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

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