Skip to the solution
EasyFrontendAsked in 20246 min read

Async filter utility

1.9k views

The problem

Problem, as an interviewer would state it: "Write an asyncFilter(items, predicate) where predicate returns a Promise<boolean>. It should behave like Array.prototype.filter, but await each async check. Show me the difference between doing this the naive way and the fast way."

Examples:

Code
const isEvenAsync = async (n) => { await delay(); return n % 2 === 0; };
await asyncFilter([1,2,3,4,5,6], isEvenAsync); // [2, 4, 6]

Clarifying questions expected:

  • Do the async checks need to run in a specific order relative to each other, or is running them concurrently fine?
  • Should a rejected predicate call fail the whole operation, or be treated as false?
  • Is there a concurrency limit needed, or can every check run at once regardless of items.length?

Code / implementation expected: Yes — real, direct proof that a sequential and a parallel implementation produce identical results, with the parallel version measurably faster on real, independently-delayed async checks.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: sequential and parallel async filtering produce identical results, with parallel measured ~5.8x faster on real timed checks

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 12 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Document tree depth check

Continue