How to use filter and Promise.all In Javascript

In this approach, we use Promise.all to handle the asynchronous operations and filter the array based on the results.

Example: To demonstrate filtering an array using an asynchronous function that returns a promise using filter and Promise.all

JavaScript
async function filterAsync(array, asyncCallback) {
    
    const filterResults = await Promise
        .all(array.map(asyncCallback));

    return array
        .filter((_, index) => filterResults[index]);
}

async function isEvenAsync(num) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(num % 2 === 0);
        }, 100);
    });
}

(async () => {
    let numbers = [1, 2, 3, 4, 5, 6];

    let evenNumbers = await filterAsync(numbers, isEvenAsync);

    console.log("Even Numbers:", evenNumbers);
})();

Output
Even Numbers: [ 2, 4, 6 ]

Time complexity: O(n)

Auxiliary Space: O(n)

JavaScript Program to Filter an Array with a Function that Returns a Promise

Given an array, our task is to filter its elements using an asynchronous function that returns a promise. This function will determine whether an element should be included in the resulting array.

Example:

Input:   numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Output: Even Numbers: [ 2, 4, 6, 8, 10 ]

Below are the approaches to filter an array using an asynchronous function that returns a promise in JavaScript:

Table of Content

  • Using filter and Promise.all
  • Using for…of and await

Similar Reads

Using filter and Promise.all

In this approach, we use Promise.all to handle the asynchronous operations and filter the array based on the results....

Using for...of and await

In this approach, we use a for…of loop with await to handle each element asynchronously and filter the array based on the results....