Skip to content

Instantly share code, notes, and snippets.

@materkel
Created August 9, 2020 00:38
Show Gist options
  • Save materkel/c995e82f998f0663a6dc2ec748d749ea to your computer and use it in GitHub Desktop.
Save materkel/c995e82f998f0663a6dc2ec748d749ea to your computer and use it in GitHub Desktop.
filter array with multiple conditions by making use of destructuring
function filterByConditions(arr: any[], ...filterFunctionConditions: Function[]): any[][] {
const results = [[]];
filterFunctionConditions.forEach(() => results.push([]));
for (const value of arr) {
let conditionMet = false;
for (let i = 0; i < filterFunctionConditions.length; i++) {
if (filterFunctionConditions[i](value)) {
results[i].push(value);
conditionMet = true;
break;
}
}
if (!conditionMet) {
results[results.length - 1].push(value);
}
}
return results;
}
const fruits = ['apple', 'orange', 'orange', 'apple', 'strawberry', 'banana', 'banana', 'raspberry'];
const conditions = [
(val) => val === 'apple',
(val) => val === 'orange',
(val) => val === 'banana'
]
const [apples, oranges, bananas, otherFruits] = filterByConditions(fruits, ...conditions);
// [ 'apple', 'apple' ] [ 'orange', 'orange' ] [ 'banana', 'banana' ] [ 'strawberry', 'raspberry' ]
console.log(apples, oranges, bananas, otherFruits]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment