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

363
Views
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 answers
Answer question

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 Report

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 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!