I have a number array ranging from 1 to 20. My goal is to create a loop that extracts every nth element from the array, starting with (1, 6, 11, 16). After the initial loop, it should then extract every 5th element, starting from 2 (2, 7, 12, 17).
My attempt:
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:
[1, 6, 11, 16, 2, 7, 13, 19, 3, 8, 15, 4, 9, 17, 5, 10, 19, 6, 11]
Expected Output:
[1, 6, 11, 16, 2, 7, 12, 17, 3, 8, 13, 18, 4, 9, 14, 19, 5, 10, 15, 20]