Reputation: 2381
I'm calculating the distance from points to the origin. It's a basic math calculation: Math.sqrt( Math.pow(x-0, 2) + Math.pow(y-0, 2) )
For testing, I have the points: points = [[1,3],[-2,2]]
. I would like to sort it based on the smallest distance to the origin.
My code:
points.sort((a,b) => {
const d1 = Math.sqrt( Math.pow(a[0], 2) + Math.pow(a[1], 2) );
const d2 = Math.sqrt( Math.pow(b[0], 2) + Math.pow(b[1], 2) );
return d1 <= d2 ? a-b : b-a;
});
console.log(points);
The log is showing: [[1,3],[-2,2]]
The 2D array is not changing. The calculation is right in the sort function. I'm not sure why it is not working.
Upvotes: 1
Views: 42
Reputation: 386736
You need to take the delta of the distances.
var points = [[1, 3], [-2, 2]];
points.sort((a, b) => {
const d1 = Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2));
const d2 = Math.sqrt(Math.pow(b[0], 2) + Math.pow(b[1], 2));
return d1 - d2;
});
console.log(points);
An even shorter approach uses Math.hypot
.
var points = [[1, 3], [-2, 2]];
points.sort((a, b) => Math.hypot(...a) - Math.hypot(...b));
console.log(points);
Upvotes: 3