Created
November 19, 2021 08:58
-
-
Save SavvasStephanides/f3517e2410ad4061ece32ff277d702b0 to your computer and use it in GitHub Desktop.
Implement 'filter' with reduce.
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
// Credit: Tweet from @oliverjumpertz: https://twitter.com/oliverjumpertz/status/1460184236917460993 | |
// Filtering means: Test all elements of an array and take those with you that succeed the test | |
const filter = (array, callback) => array.reduce((accumulator, current, index, arr) => { | |
// This is the filter function. It decides which element is added to the new array | |
if (callback(current, index, arr)) { | |
// For each iteration, the current element is tested with the callback. If that test succeds | |
// it's added to the resulting array. | |
accumulator.push(current); | |
} | |
return accumulator; | |
// You want a new array as the initial value | |
}, []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment