Last active
July 23, 2016 07:34
-
-
Save shakdwipeea/cb988b3a91ebc5b989d4657c34703944 to your computer and use it in GitHub Desktop.
Split array of objects
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
/** | |
* 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