-3

Writing code in C/C++ way when we had to iterate an array we wrote

for(int index = 0; index < array.size(); index++) {
     doSomething(index);
}

when it was necessary to iterate by 4 we wrote

for(int index = 0; index < array.size(); index = index + 4) {
     doSomething(1, index);
     doSomething(2, index+1);
     doSomething(3, index+2);
     doSomething(4, index+3);
}

How can I achieve this by using JavaScript's map reduce or filter array functions?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
chatzich
  • 1,083
  • 2
  • 11
  • 26
  • 1
    Possible duplicate of [Loop through an array in JavaScript](https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript) – adiga Jul 28 '19 at 09:43
  • Why you want to do that with `map`, `reduce` or `filter`? is there any logical reason for not using a regular for loop or an iterator? None of the three prototypes was built to be used for that purpose. – briosheje Jul 28 '19 at 09:56

2 Answers2

3

You can do it with a normal loop in JavaScript:

for(let index = 0; index < array.length; index += 4) {
     doSomething(1, index);
     doSomething(2, index + 1);
     doSomething(3, index + 2);
     doSomething(4, index + 3);
}

Also with forEach and modulus:

array.forEach((e, i) => {
  if (!(i % 4)) return;
  doSomething(1, i);
  doSomething(2, i + 1);
  doSomething(3, i + 2);
  doSomething(4, i + 3);
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You can't achieve this with map or filter or other array functions, cause they do something for every element of the array.

But you can achieve this with the same syntax that you use in c/c++ with a for loop:

for(let index = 0; index < array.length; index += 4) {
     console.log(index);
}
Sinandro
  • 2,426
  • 3
  • 21
  • 36