Last active
August 21, 2020 23:56
-
-
Save AyAyEm/1ade64267fab649f275145e773dd8809 to your computer and use it in GitHub Desktop.
An array filter but designed to return both true and false values.
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
/** | |
* 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