Last active
February 19, 2024 14:12
-
-
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
This file contains hidden or 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
// 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