Skip to content

Instantly share code, notes, and snippets.

@JonCatmull
Created December 18, 2020 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonCatmull/8993253a9b26dee4b44afd5f5cbfe26a to your computer and use it in GitHub Desktop.
Save JonCatmull/8993253a9b26dee4b44afd5f5cbfe26a to your computer and use it in GitHub Desktop.
Split an array based on predicate function.
/**
* Splits array when splitOn function returns true. Matched item will kept and be first in the subsequent child array.
* @param items
* @param splitOn
*/
export const splitArray = <T>(
items: T[],
splitOn: (item: T) => boolean,
keepSplitItem = true
): T[][] => {
if (!items.length) return [];
// split array by separators
let master: T[][] = [];
let split: T[] = [];
items.forEach((item) => {
if (splitOn(item)) {
if (split.length) {
master.push(split);
}
// add matched item to start of new sub split array
if (keepSplitItem) {
split = [{ ...item }];
} else {
split = [];
}
} else {
split.push({ ...item });
}
});
// catch any remaining items
if (split.length) {
master.push(split);
}
return master;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment