Home > front end >  When using Array.map() followed by a for loop on that same array, is it double work?
When using Array.map() followed by a for loop on that same array, is it double work?

Time:12-18

I'm perplexed why a previous engineer wrote some code that looks like double work to me. Could you not just do either the accounts.map() or the for (const acct of accounts)? Why both?

const accounts = await mongohelper.find(conn, 'accounts', query, 2000);
if(!accounts.length){return;}
const arrayofwork = accounts.map(act => salesmanwork(act, conn))


for (const act of accounts) {
    arrayofwork.push(salesmanwork(act, conn));
}

await Promise.allSettled(arrayofwork)
return await recursivecall(workitemin, count);

CodePudding user response:

It's making a duplication of the processed values from the accounts array by salesmanwork function. Maybe that's what's intended or might be a bug, some code that they didn't remove.

CodePudding user response:

Output is basically the same, the only differences are speed, readability and functionality, which barely differ. What I mean by this is that when using .map() it returns an array, in where you can use it in one-liners and promises, while in for loops, you need to initialize, then make the loop, and return the same value.

In this case, it is probably some code someone forgot to clean up; either works, the only differences are readability. If you are using a bigger array, use the for loop, otherwise it's up to you.

  • Related