Created
August 9, 2020 00:38
-
-
Save materkel/c995e82f998f0663a6dc2ec748d749ea to your computer and use it in GitHub Desktop.
filter array with multiple conditions by making use of destructuring
This file contains hidden or 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
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