FrontendPro

43Implement asyncFilter() with asynchronous predicates

mediumAbout 35 minutesCodingpromisesasyncarrays

Problem

array.filter(async (x) => …) does not work: every async function returns a promise, and a promise is always truthy, so nothing is removed.

Implement asyncFilter(items, predicate). It calls the async predicate(item, index) for every item in parallel and resolves to the items whose predicate resolved to a truthy value, in their original order.

const reachable = await asyncFilter(urls, async (url) => {
  const res = await fetch(url, { method: "HEAD" });
  return res.ok;
});

Requirements

  • Run all predicates in parallel.
  • Keep the original order of the kept items.
  • Any truthy resolved value keeps the item.
  • Reject if any predicate rejects or throws.
  • Accept any iterable; an empty input resolves to [].

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

Copy the iterable into an array first, so you can index it later and so a generator is only consumed once.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever