Skip to content

Instantly share code, notes, and snippets.

@shakdwipeea
Last active July 23, 2016 07:34
Show Gist options
  • Save shakdwipeea/cb988b3a91ebc5b989d4657c34703944 to your computer and use it in GitHub Desktop.
Save shakdwipeea/cb988b3a91ebc5b989d4657c34703944 to your computer and use it in GitHub Desktop.
Split array of objects
/**
* Split array
* @param arr[] The array to split
* @param startFn Start condition
* @param endFn End condition
*/
function chunk(arr, startFn, endFn) {
var chunks = [];
var chunk = [];
for (let elem of arr) {
if (startFn(elem)) {
chunk = [];
}
chunk.push(elem);
if (endFn(elem)) {
chunks.push(chunk);
chunk = [];
}
}
return chunks;
}
var arr = [
{
id: 23,
source: "a"
},
{
id: 32,
source: "b"
},
{
id: 42,
source: "c"
},
{
id: 13,
source: "a"
},
{
id: 12,
source: "d"
},
{
id: 14,
source: "c"
}
];
var ans = chunk(arr, (e) => e.source === "a", (e) => e.source === "c");
console.log(ans);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment