Filter an array with an async predicate
Filtering a list of documents by whether the current user may see each one means asking the server per document. You want those checks to run together, but the surviving items must still appear in their original order.
Implement filterAsync(items, predicate). Call predicate(item, index) for every item, starting all of the calls before awaiting any of them. Resolve with a new array containing the items whose awaited result is truthy, in their original order. An empty array resolves with an empty array, and the input array is never mutated. If any predicate rejects, reject with the first rejection reason.
Arguments
itemsArray<T>- The input array to filter.
predicate(item: T, index: number) => boolean | Promise<boolean>- The async check for each item.
Returns
Promise<Array<T>> — A promise that resolves with the surviving items in original order. Rejects with the first rejection reason.
Examples
const evens = await filterAsync(
[1, 2, 3, 4, 5, 6],
async (n) => n % 2 === 0
);
// evens === [2, 4, 6]Standard filter semantics with an async predicate.
const kept = await filterAsync(
["a", "b", "c", "d"],
(item, index) =>
new Promise((resolve) => setTimeout(() => resolve(index !== 1), (4 - index) * 8))
);
// kept === ["a", "c", "d"] — order preserved even though checks finished out of orderResults stay in input order regardless of which check finishes first.
What it has to do
- Start every predicate call before awaiting the results.
- Keep the surviving items in their original order.
- Pass the index to the predicate as the second argument.
- Do not mutate the input array.
- Reject with the first rejection reason if a predicate fails.
Notes
- Run every predicate first, collect the boolean array, then filter the originals by matching index — otherwise you lose order.
- An empty input resolves with
[]without calling the predicate.
Stuck? The javascript course covers everything this challenge needs.
- 1.keeps the items whose predicate is truthy
- 2.keeps the original order when checks finish out of order
- 3.runs the predicates concurrently
- 4.returns an empty array and leaves the input alone
- 5.rejects when a predicate rejects
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.