Home > Software engineering >  how to transform two for loops into array method
how to transform two for loops into array method

Time:01-03

const mergeResults = async (items: string[]): Promise<MyArray[]> => {
  let itemsArray = []

for(let i = 0; i < items.length; i  ) {
    let itemsFilter = await testMyData(items[i])
   for(let j = 0; j < itemsFilter.length; j  ) {
       itemsArray.push(itemsFilter[j])
   }
}
  return itemsArray;
};

I intend to transform this part of the code into:

.map or .forEach method

for(let i = 0; i < items.length; i  ) {
    let itemsFilter = await testMyData(items[i])
   for(let j = 0; j < itemsFilter.length; j  ) {
       itemsArray.push(itemsFilter[j])
   }
}

CodePudding user response:

You're making an asynchronous request for each item in items, and need to wait for the resolution of each such request, so .map in combination with Promise.all would be more appropriate, if the testMyData function can handle it. You only need a items.map(testMyData) to get an array of Promises, and then .flat() to flatten the values afterwards.

const mergeResults = async (items: string[]): Promise<MyArray[]> => {
    const nestedResults = await Promise.all(items.map(testMyData));
    return nestedResults.flat();
};

That said, note that this invokes testMyData many times synchronously - in contrast, your original code invokes it only in serial, after the last iteration's test has completed. Running in parallel has the potential to be much faster, but it also has the potential to overload whatever resources testMyData requires, so be aware.

The return type of MyArray[] doesn't sound quite right. The logic being performed is to convert an asynchronously retrieved 2D array of test results into a flat array of results. Unless each test result is an array itself, calling a single result a MyArray sounds misleading. Perhaps call that type TestResult instead, so that you have Promise<TestResult[]>.

  • Related