skip to Main Content

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


  1. 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))
    Login or Signup to reply.
  2. Here’s my approach using a good old nested for.

    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++) {
      for (let j = i; j < cellArray.length; j += row) {
        newArray.push(cellArray[j]);
      }
    }
    
    console.log(newArray);
    Login or Signup to reply.
  3. You could use also Array::reduce():

    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 = Array.from({length: row})
      .reduce((r, _, i) => (cellArray.forEach((item, k) => k % row === i && r.push(item)), r), []);
    
    console.log(JSON.stringify(newArray))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search