Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find the total distance of point on x axis in js?

I am creating a program in JavaScript that will detect the line is in parallel to x or Y axis so here I want to distance of 5+3-2=6 for total distance but here I get the distance of 5+3=8 and 5-2=3 so how to do like that I will get the result like 5+3-2.code is given below

let points = [
    [3, 3],
    [3, 5],
    [3, -2]
  ];
  for (let i = 0; i < points.length-1; i++) {
    if (points[i][0] !== points[i + 1][0]) {
      console.log("|| to Y and distance");
    } else if (points[i][1] !== points[i + 1][1]) {
      console.log("|| to X and distance",points[i+1][1]+points[i][1]);
    }
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let points = [  [3, 3],
  [3, 5],
  [3, -2]
];

let totalDistance = 0;
for (let i = 0; i < points.length-1; i++) {
  if (points[i][0] !== points[i + 1][0]) {
    console.log("|| to Y and distance");
    totalDistance += Math.abs(points[i + 1][0] - points[i][0]);
  } else if (points[i][1] !== points[i + 1][1]) {
    console.log("|| to X and distance");
    totalDistance += Math.abs(points[i + 1][1] - points[i][1]);
  }
}
console.log("Total distance:", totalDistance);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading