Advertisements

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 :

```
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);
```