Skip to content

Instantly share code, notes, and snippets.

@materkel
Last active August 6, 2020 14:03
Show Gist options
  • Save materkel/7c725838d44204da6eda4ac3e0889bf9 to your computer and use it in GitHub Desktop.
Save materkel/7c725838d44204da6eda4ac3e0889bf9 to your computer and use it in GitHub Desktop.
return both true and false values from filtering an array (with destructuring)
function divideBy(arr: any[], divideFn: Function) {
return arr.reduce((agg, curr) => divideFn(curr) ?
[[...agg[0], curr], agg[1]] :
[agg[0], [...agg[1], curr]],
[[], []]);
}
const fruits = ['apple', 'orange', 'banana'];
const divideFn = (fruit) => fruit === 'apple';
const [apples, otherFruits] = divideBy(fruits, divideFn);
// ['apple'] ['orange', 'banana'];
console.log(apples, otherFruits]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment