Kasra GH
Kasra GH

Reputation: 157

Async foreach in javascript with step of n

If I run this, I will get 1, 2, ..., 50 in my console.

keys = [1, 2, 3, ..., 50];
async.forEach(keys, function (key, callback){
    console.log(key);
    callback();
}

But I want to have an step of 3. I want to get: 1, 4, 7, ... like this for loop:

for (let key = 1; key <= 50; key = key + 3) {

}

How can I achieve this with async?

Upvotes: 2

Views: 1912

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50844

const res = keys.reduce((acc, elem, i) => i % 3 == 0 ? [...acc, elem] : acc, []);

Will give you the result res of:

[1, 4, 7, 10, 13, ..., 48]; // Every 3rd index

Where i % 3 controls the step. So, if you want to increment by 4 each time you could change this to i % 4 etc...

Thus, you can use this in your code like so:

keys = [1, 2, 3, ..., 50];
let stepKeys = keys.reduce((acc, elem, i) => i % 3 == 0 ? [...acc, elem] : acc, []);
async.forEach(stepKeys, function (key, callback){
    console.log(key);
    callback();
}

Upvotes: 1

abdullahkady
abdullahkady

Reputation: 1071

I'm not sure what async.forEach is, but assuming you're just trying to do a normal forEach with 3 steps as you said, here's my approach:

forEach is not really appropriate for usages where you manipulate your index (specially in more hardcore cases, where your index might change within the loop), but as a quick hack, you can do the following:

keys.forEach((key, index) => {
  if(index % 3 === 0) {
  // Only true when it's a multiple of 3
  // Do your loop body
  } 
});

Note that forEach takes a callback, where the first parameter is the current value, and optional parameters (among which is the current index), see the docs

Upvotes: 4

Related Questions