skip to Main Content

Looking to create a function in (vanilla) JavaScript that generates an array with n values between a min and max value, where n is a specified number of steps. The first value should be the min, the last should be the max.

i.e.

function returnAllSteps(min,max,totalSteps) {
  var steps = new Array(totalSteps);
  for (i = 0; i < totalSteps; i++) {
    steps[i] = // HELP: return number value between min and max?
  }
  console.log(steps);
}
returnAllSteps(0,10,30); // min = 0, max = 10, totalSteps = 30 (give me an array with 30 steps between 0 and 10)

I would also like to be able to return a single step value within the range. Does this have to happen in a different function?

i.e.

function returnStep(min,max,totalSteps,stepNumberToReturn) {
  // HELP: do I even need another function to do this?
}
returnStep(0,10,30,20); // min = 0, max = 10, totalSteps = 30, stepNumberToReturn = 20
// Return the value at array[20 - 1]

Any help would be much appreciated!

2

Answers


  1. Only one function is needed to generate and return an array with all steps:

    function returnAllSteps(min, max, totalSteps) {
      let steps = new Array(totalSteps);
      let distance = max - min;
      for (i = 0; i < totalSteps; i++) {
        steps[i] = min + distance * (i / (totalSteps - 1));
      }
      return steps;
    }
    
    let mySteps = returnAllSteps(0, 10, 30); // min = 0, max = 10, totalSteps = 30 (give me an array with 30 steps between 0 and 10)
    console.log(mySteps);

    Then just get the step you need from mySteps directly. For example: mySteps[20]

    Login or Signup to reply.
  2. Calculate the value of a step, and then use Array.from() to create the array:

    function returnStep(min, max, totalSteps) {
      const step = (max - min) / totalSteps
    
      return Array.from({ length: totalSteps }, (_, i) => i * step + min)
      
    }
    
    console.log(returnStep(0,10,20))

    To find a specific number you get use the formula for arithmetic progression:

    function returnStep(min,max,totalSteps,stepNumberToReturn) {
      const d = (max - min) / totalSteps
      
      return min + d * (stepNumberToReturn - 1)
    }
    
    console.log(returnStep(0,10,20,10))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search