Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for loop conditional iterations and resetting variable

With the following code, I'm looping through an array of colors (favorites), creating rectangles for a jsPDF document.

After 5 iterations, I want to reset the x variable back to startX and then add 1.875 with each iteration. Likewise for the next 5 iterations: reset x to startX adding 1.875 until 10, then again until 15.

I'm just not having any luck resetting x in these conditionals. I'm sure it's something obvious but what am I missing here?

Or should I structure the loop in a different way?

What I'm trying to accomplish is create up to 3 rows of 5 rectangles. Once I hit 5, start a new row, hence the reset of x which is a page location coordinate.

let startX = 1
let startY = 1

let secondY = 4
let thirdY = 6.5

let n = favorites.length

for (let i = 0, x = startX, y = startY; i < n; x += 1.875, i++) {
    if (i < 5) {
        doc.setFillColor(favorites[i].h)
        doc.rect(x, y, 1.5, 1, 'F')
        doc.text(favorites[i].h.toString(), x, y + 1.5)
    } else if (i >= 5 && i < 10) {
        x = 1 // resets but then doesn't increment
        y = secondY
        doc.setFillColor(favorites[i].h)
        doc.rect(x, y, 1.5, 1, 'F')
        doc.text(favorites[i].h.toString(), x, y + 1.5)
    } else if (i >= 10 && i < 15) {
        x = 1 // resets but then doesn't increment
        y = thirdY
        doc.setFillColor(favorites[i].h)
        doc.rect(x, y, 1.5, 1, 'F')
        doc.text(favorites[i].h.toString(), x, y + 1.5)
    }
}
like image 369
joshuaiz Avatar asked Apr 08 '26 02:04

joshuaiz


1 Answers

You can use the modulo operator (%), and set x and y outside the loop declaration:

const yValues = [1, 4, 6.5];

for (let i = 0 ; i < 15; i++) {
  const x = 1 + ((i%5) * 1.875);
  const y = yValues[Math.floor(i/5)];
  // commented lines to make this example run
  // doc.setFillColor(favorites[i].h)
  // doc.rect(x, y, 1.5, 1, 'F')
  // doc.text(favorites[i].h.toString(), x, y + 1.5)  
  console.log({x,y});
}
like image 74
Pablo Lozano Avatar answered Apr 09 '26 14:04

Pablo Lozano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!