Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
Shorten for-loops into one

is it possible to shorten these three for loops into one the code works absolutely fine, I just want to know if there is a possibility to shorten these three for loops into one for exercising reasons and also for code-readability

let board_coord = []

for (let i = 0; i < 3; i++) {
  board_coord.push({
    x: i * 166,
    y: 0
  })
}
for (let j = 0; j < 3; j++) {
  board_coord.push({
    x: j * 166,
    y: 166
  })
}
for (let k = 0; k < 3; k++) {
  board_coord.push({
    x: k * 166,
    y: 332
  })
}

console.log(board_coord)

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you mean a single top level loop, you could use a nested loop:

const SIZE = 166;
let boardCoord = [];
for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        boardCoord.push({ x: SIZE * j, y: SIZE * i });
    }
}

I don't think a single loop overall would be any more readable than this.

about 4 years ago · Juan Pablo Isaza Report

0

A single loop would require a little math. (see: Remainder (%) and Math.floor())

const boardCoord = [];

for (let i = 0; i < 9; i++) {
  boardCoord.push({
    x: (i % 3) * 166,
    y: Math.floor(i / 3) * 166
  })
}

console.log(boardCoord)

Or generalized...

const WIDTH = 3;
const HEIGHT = 3;
const SCALE = 166;

const boardCoord = [];
for (let i = 0; i < WIDTH * HEIGHT; i++) {
  boardCoord.push({
    x: (i % WIDTH) * SCALE,
    y: Math.floor(i / WIDTH) * SCALE
  })
}

console.log(boardCoord)

But it's not necessarily more readable than a nested loop which can also be generalized.

const COLS = 3;
const ROWS = 3;
const SCALE = 166;

const boardCoord = [];
for (let row = 0; row < ROWS; row++) {
  for (let col = 0; col < COLS; col++) {
    boardCoord.push({ x: SCALE * col, y: SCALE * row });
  }
}
console.log(boardCoord)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!