Skip to content

Instantly share code, notes, and snippets.

@tomfordweb
Last active October 30, 2018 15:31
Show Gist options
  • Save tomfordweb/d64d29364a2bc8a59bc8050758c4dd8f to your computer and use it in GitHub Desktop.
Save tomfordweb/d64d29364a2bc8a59bc8050758c4dd8f to your computer and use it in GitHub Desktop.
Chunk Array - ES6
/**
* Non-destructive chunk method for arrays
*/
export const chunk = (array, chunk) => {
var i, j, temparray = [];
for (i = 0, j = array.length; i < j; i += chunk) {
temparray.push(array.slice(i, i + chunk));
// do whatever
}
return temparray;
}
import { expect } from 'chai';
it('can chunk an array', () => {
const original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const expected = [
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10]
];
expect(chunk(original, 2)).to.eql(expected);
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment