james james - 1 month ago 10
Javascript Question

Does JavaScript have a method that returns an array of numbers based on start, stop and desired number of return values?

I'm looking for something similar to numpy.linspace to generate an array of numbers based on a starting value, an ending value and the desired number of values in the array.

example:
start=2.0, end=3.0, num=5
result = [2.0, 2.25, 2.5 , 2.75, 3.0]


I've come across this, but it separates the range based on the steps between.

Does JavaScript have a built-in method to accomplish this?

Answer

As others mentioned, there is no built in function in JavaScript, but here's one way you can implement it yourself. This specific example is a bit verbose so you can see exactly what's going on. Hope it helps!

function makeArr(startValue, stopValue, cardinality) {
  var arr = [];
  var currValue = startValue;
  var step = (stopValue - startValue) / (cardinality - 1);
  for (var i = 0; i < cardinality; i++) {
    arr.push(currValue + (step * i));
  }
  return arr;
}

console.log(makeArr(2, 3, 5));
console.log(makeArr(5, 10, 5));
console.log(makeArr(5, 10, 6));
console.log(makeArr(5, 31, 4));

Update: If you want the numbers to be rounded to 2 decimal places, you can change the arr.push(...) line to the following:

arr.push(parseFloat((currValue + (step * i)).toFixed(2)));

Or

arr.push(Math.round((currValue + (step * i)) * 100) / 100);