Back to Async / PromisesMedium
Exercise 18: Promise Filter (async condition)
Problem Statement
Function `promiseFilter(arr, fn)` banao jo array ko async condition se filter kare.
Example: promiseFilter([1,2,3], async (x) => x > 1)
Sample Output:
await promiseFilter([1,2,3], async (x) => x > 1) => [2, 3] // Filters with async condition
Solution
const promiseFilter = async (arr, fn) => {
const results = await Promise.all(arr.map(async (item, index) => ({item, index, keep: await fn(item, index)})));
return results.filter(r => r.keep).map(r => r.item);
};Explanation
Overall Goal:
- Array ko async condition se filter karna.
Real world:
- Async filtering: condition checks.
- Data processing: async filters.