Skip to content

Instantly share code, notes, and snippets.

@hayk94
Created September 29, 2017 05:53
Show Gist options
  • Save hayk94/720438d7830ff11bbd4b50c7cf23301e to your computer and use it in GitHub Desktop.
Save hayk94/720438d7830ff11bbd4b50c7cf23301e to your computer and use it in GitHub Desktop.
Chunk array by element or split array like a string
/**
* chunkArrayByElement - Chunk array by element or split array like a string
*
* @param {Array} arr array to chunk
* @param {Any} c element to chunk by
* @return {Array} array containing chunk arrays
*/
// https://stackoverflow.com/questions/46468754/chunk-array-by-element
function chunk(arr, el) {
if (arr.length === 0) {
return arr
}
return arr.reduce((prev, curr, index) => {
if (curr === el) {
if (index === 0 || index === arr.length - 1) {
return prev
}
if (prev[prev.length - 1].length !== 0) {
prev.push([]);
}
} else {
prev[prev.length - 1].push(curr);
}
return prev;
}, [[]]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment