How to restrict HTML column elements based on maximum value of field in array of objects

Viewed 102

I have a pug template that receives an array of objects from Node/mongo/express. Based on the maximum value of one the fields (not length), I need to restrict some columns in an html table.

For example, the objects rendered from node might look like this

{
    quantity: 4,
    years: 6
},
{
    quantity: 78,
    years: 2
}

I would then need to restrict the number of 'year' columns in my table to be 6. I'm not sure what the best way is to do this, whether to render an additional 'max' variable in node, whether I can do this in pug, or if I should use some client-side js. In (very) pseudo-code, I want something like this...

forEach(Math.max(project.output.years)){
     ...create an html table 'year' column
}
2 Answers

I'm not sure if pug is the right tool for doing this kind of data manipulation.

From the nodejs side, you could use a reducer to find the maximum years value and send it down with the rest of your data.

const data = [{
    quantity: 4,
    years: 6,
  },
  {
    quantity: 78,
    years: 2,
  },
]

const maxYears = data.reduce((acc, current) => current.years >= acc ? current.years + acc : acc, 0)

console.log(maxYears) // 6

Or make the reducer a bit more flexible in terms of which field it accesses to make a comparison.

const data = [{
    quantity: 4,
    years: 6,
  },
  {
    quantity: 78,
    years: 2,
  },
]

const findMaxVal = (property, data) =>
  data.reduce(
    (accumulator, current) =>
    current[property] > accumulator ? current[property] : accumulator,
    0
  )

console.log(findMaxVal("years", data)) // 6

There are a number of ways to find the max, but the easiest is:

var maxYears = 0;
for(var i = 0 ; i < data.length ; i++){
  if( data[i].years > maxYears ){
    maxYears = data[i].years;
  }
}

(I'm assuming that the array you have all those objects in is called data)

Then you can pass maxYears into the pug template and do this:

table
  tr
    - var col = 0;
    while col < maxYears
      td(colIndex= col++)

This will produce a table that looks like this for maxYears = 3:

<table>
  <tr>
    <td colIndex='0'></td>
    <td colIndex='1'></td>
    <td colIndex='2'></td>
  </tr>
</table>

Just repeat that loop for every row.

Related