Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 266
james Avatar asked Nov 07 '16 21:11

james


2 Answers

As others mentioned, there isn’t any 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.

function makeArr(startValue, stopValue, cardinality) {
  var arr = [];
  var step = (stopValue - startValue) / (cardinality - 1);
  for (var i = 0; i < cardinality; i++) {
    arr.push(startValue + (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));

If you want the numbers to be rounded to two 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);

like image 74
mhodges Avatar answered Oct 20 '22 02:10

mhodges


You can make use of Array.from instead of manually pushing to the array:

function linspace(start, stop, num, endpoint = true) {
    const div = endpoint ? (num - 1) : num;
    const step = (stop - start) / div;
    return Array.from({length: num}, (_, i) => start + step * i);
}

Note that this won't work for num=1 and endpoint=true.

like image 37
STJ Avatar answered Oct 20 '22 00:10

STJ