Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a calculated array based on limits

OK time to pick the hive mind brain.

I am creating a dropdown (well 2 of them) and I need them to do the following
Height from 4’0" to 7’0"
Weight from 100lb to 400lb in 5lb incraments.

What would be the best/easiest way to create this array without having to manually create an array

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It just needs to be as simple as

const heights = [
    { id: '', name: '' },
]

I just to not know how to best create it in as few Lines of code or manually creating the array

Same with height in 5lb increments

EDIT: SO people know WHY I am asking this – try doing a google search and enjoy the frustration.

>Solution :

For the weights, you can use the Array.fill function as seen in this answer.

// https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp

const range = (start, stop, step = 1) =>
  Array(Math.ceil((stop - start) / step) + 1).fill(start).map((x, y) => x + y * step)

const weights = range(100, 500, 5).map((x, index) => ({
  id: index,
  name: x
}))

console.log(weights)

// or with one line of code

const w = Array(Math.ceil((500 - 100) / 5) + 1).fill(100).map((x, index) => ({
    name: x + index * 5, id: index
}))
console.log(w)

For the heights, you can use a simple algorithm as a while loop with a condition for the increment

const start = {
  integer: 4,
  fractionnal: 0
}
const end = {
  integer: 7,
  fractionnal: 0
}

const heights = []

let index = 1
while (start.integer < end.integer || start.fractionnal <= end.fractionnal) {
  heights.push({
    id: index,
    name: `${start.integer}.${start.fractionnal}`
  })

  if (start.fractionnal < 11) start.fractionnal += 1
  else {
    start.integer += 1
    start.fractionnal = 0
  }
}

console.log(heights)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading