2

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?

1
  • 1
    If keys is set to [1, 2, 3... initially, just multiply by 3 and subtract to get to 1, 4, 7 on each iteration? Is that what you mean? Commented Nov 18, 2018 at 7:18

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

This answer is much more transparent
1

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.