How to generate array of n equidistant points along a line segment of length x with JavaScript?


To generate array of n equidistant points along a line segment of length x, use the below syntax −

for (var anyVariableName= 0; yourVariableName< yourStartPointName;
yourVariableName++) {
   var v = (yourVariableName+1)/ (yourStartPointName+1);
   var v2 = v*yourEndPointName;

Example

function drawPoints(start, end) {
   const arrayOfPoints = []
   for (var index = 0; index < start; index++) {
      var v = (index+1)/ (start+1);
      var v2 = v*end;
      arrayOfPoints.push(Math.round(v2));
   }
   return arrayOfPoints;
}
const arrayOfPoints = drawPoints(5, 50);
console.log("The Points=");
console.log(arrayOfPoints);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo53.js

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo54.js
The Points= [ 8, 17, 25, 33, 42 ]

Updated on: 03-Sep-2020

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements