Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda