Skip to content

Instantly share code, notes, and snippets.

@florianpasteur
Last active February 19, 2024 14:12
Show Gist options
  • Save florianpasteur/c480dbeb9b699015ca6de8aa5888ffa6 to your computer and use it in GitHub Desktop.
Save florianpasteur/c480dbeb9b699015ca6de8aa5888ffa6 to your computer and use it in GitHub Desktop.
Filter an array and split the array into 2 arrays, one with the elements matching the predicate and one with the elements rejected by the predicate
// const filteredArray = myArray.filter(str => str.length > 255);
// becomes
// const [filteredArray, rejectedArray] = myArray.filterSplit(str => str.length > 255);
declare global {
interface Array<T> {
filterSplit(predicate: (item: T, index: number, array: T[]) => boolean): [T[], T[]];
}
}
Array.prototype.filterSplit = function<T>(predicate: (item: T, index: number, array: T[]) => boolean): [T[], T[]] {
const matched: T[] = [];
const rejected: T[] = [];
this.forEach((item, index, array) => {
if (predicate(item, index, array)) {
matched.push(item);
} else {
rejected.push(item);
}
});
return [matched, rejected];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment