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

373
Vistas
Given a total # of items and items per row, what column does an item belong to?

I have an application using CSS grid which will contain an variable number of grid elements, although I'll know the # of items in each row - is there an easy way to determine the column # of a given item?

ie. given 32 elements arranged into rows of 8, element number 9 is in column 1, element number 10 is in column two.

Currently I'm doing this:

function getColumn(itemIndex, colsPerRow) {
  // its in the last column
  if (itemIndex % colsPerRow === 0) {
    return colsPerRow;
  }

  return itemIndex - (Math.floor(itemIndex/colsPerRow) * colsPerRow);
}

And it returns the correct answer, but I feel like there's a more simple way to solve this.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

To take 1-based numbering into account:

column = (itemIndex - 1) % colsPerRow + 1 

(no need in if clause)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You've almost got the answer already: item number modulo column count.

function getColumn(itemIndex, colsPerRow) {
  // its in the last column
  if (itemIndex % colsPerRow === 0) {
    return colsPerRow;
  }

  return itemIndex % colsPerRow;
}

console.log(
  getColumn(1,9),
  getColumn(2,9),
  getColumn(3,9),
  getColumn(4,9),
  getColumn(5,9),
  getColumn(6,9),
  getColumn(7,9),
  getColumn(8,9),
  getColumn(9,9),
  getColumn(10,9),
  getColumn(11,9)
);

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