Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trouble with Javascript loop

I have an array with numbers starting from 1 to 20. I want to write a loop that takes every n-th element in the current array, for example (1, 6, 11, 16). After the first loop, it should take every 5-th element too, but start from 2 (2, 7, 12, 17)

I tried this:

const row = 5;

const cellArray = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
];

const newArray = [];

for (let i = 0; i <= row; i++) {
  cellArray.forEach((item, k) => {
    if (k === i) {
      newArray.push(item);
    }

    console.log(i);

    if (k % (row + i) == 0 && k !== 0) {
      newArray.push(item);
    }
  });
}

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1, 6, 11, 16, 2, 7, 13, 19, 3, 8, 15, 4, 9, 17, 5, 10, 19, 6, 11]

What I expected to:

[1, 6, 11, 16, 2, 7, 12, 17, 3, 8, 13, 18, 4, 9, 14, 19, 5, 10, 15, 20]

>Solution :

Way too complicated approach, with those two separate checks you implemented there.

If the item index k modulo 5 (so row, effectively) matches i, then you want to put the item into your result array.

const row = 5;

const cellArray = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
];

const newArray = [];

for (let i = 0; i <= row; i++) {
  cellArray.forEach((item, k) => {
    if (k % row === i) {
      newArray.push(item);
    }
  });
}

console.log(JSON.stringify(newArray))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading