Home > Software engineering >  Given a total # of items and items per row, what column does an item belong to?
Given a total # of items and items per row, what column does an item belong to?

Time:05-24

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.

CodePudding user response:

To take 1-based numbering into account:

column = (itemIndex - 1) % colsPerRow   1 

(no need in if clause)

CodePudding user response:

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)
);

  • Related