AniUI Academy

Filter an array with an async predicate

mediumAsync & Promises+250 XPPractice

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 order

Results 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.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.