Created
February 28, 2019 03:52
-
-
Save joelbarbosa/eb9ff7c8711c0cdf343df22c492d3f83 to your computer and use it in GitHub Desktop.
Creates an array of elements split into groups the length of size.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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