Created
September 29, 2017 05:53
-
-
Save hayk94/720438d7830ff11bbd4b50c7cf23301e to your computer and use it in GitHub Desktop.
Chunk array by element or split array like a string
This file contains 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
/** | |
* 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