Skip to content

Instantly share code, notes, and snippets.

@SavvasStephanides
Created November 19, 2021 08:58
Show Gist options
  • Save SavvasStephanides/f3517e2410ad4061ece32ff277d702b0 to your computer and use it in GitHub Desktop.
Save SavvasStephanides/f3517e2410ad4061ece32ff277d702b0 to your computer and use it in GitHub Desktop.
Implement 'filter' with reduce.
// 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