1

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I'm don't clearly understand how the sort() method works. Could you explain why I need to take the delta?
I think I don't get what needs to be returned in the sort() method to sort an array
@myTest532myTest532, maybe you have a look here first: Array#sort. the expected result of the callback should return a value smaller than zero, if the first is smaller than the second item, zero for same items and greater than zero for all other items.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.