Skip to content

Instantly share code, notes, and snippets.

@AyAyEm
Last active August 21, 2020 23:56
Show Gist options
  • Save AyAyEm/1ade64267fab649f275145e773dd8809 to your computer and use it in GitHub Desktop.
Save AyAyEm/1ade64267fab649f275145e773dd8809 to your computer and use it in GitHub Desktop.
An array filter but designed to return both true and false values.
/**
* Filter an array into two arrays.
*
* Defined by the callbackFn, the first array will be with the true elements
* and the second array will be with the false elements.
*
* @param {Array} array
* @param {Function} callbackfn
* @param {Object} thisArg
* @return {[Array, Array]} A matrix with two arrays.
*/
function biFilter(array, callbackfn, thisArg = this) {
const [trueElements, falseElements] = [[], []];
for (let i = 0; i < array.length; i += 1) {
const element = array[i];
if (callbackfn.call(thisArg, element, i, array)) {
trueElements.push(element);
} else {
falseElements.push(element);
}
}
return [trueElements, falseElements];
}
module.exports = biFilter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment