Search code examples
javascriptarraysloops

Generate Array of Values between Min and Max


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!


Solution

  • 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]