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:
[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]
3
Answers
Way too complicated approach, with those two separate checks you implemented there.
If the item index
k
modulo5
(sorow
, effectively) matchesi
, then you want to put the item into your result array.Here’s my approach using a good old nested
for
.You could use also
Array::reduce()
: