Skip to content

Instantly share code, notes, and snippets.

@joelbarbosa
Created February 28, 2019 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelbarbosa/eb9ff7c8711c0cdf343df22c492d3f83 to your computer and use it in GitHub Desktop.
Save joelbarbosa/eb9ff7c8711c0cdf343df22c492d3f83 to your computer and use it in GitHub Desktop.
Creates an array of elements split into groups the length of size.
// chunk
// Creates an array of elements split into groups the length of size.
const chunk = (input, size) => {
return input.reduce((arr, item, idx) => {
if (idx % size === 0) {
return [...arr, [item]];
} else {
return [...arr.slice(0, -1), [...arr.slice(-1)[0], item]];
}
}, []);
}
const arr = chunk(['a', 'b', 'c', 'd'], 2);
console.log(arr) // [["a", "b"], ["c", "d"]]
const arr2 = chunk(['a', 'b', 'c', 'd'], 3);
console.log(arr2) // [["a", "b", "c"], ["d"]]
console.log([...['a', 'b'], 'c'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment