I have an array of degrees, [10, 90, 200, 280, 355] for a circle.
I'm given a degree, let's say 1. How do I determine that 1 is closest to 355 degrees?
Subtract the two numbers. If the difference is larger above 180 [or below -180], subtract [or add] 360. Now you can just compare absolute values of the difference.
Here is an actual formula:
degreediff = min(abs(x-y),360-abs(x-y))
This is more compact and efficient:
function difference(a, b) {
var d = Math.abs(a - b);
return d > 180 ? 360 - d : d;
};
function closest(a, bs) {
var ds = bs.map(function(b) { return difference(a, b); });
return bs[ds.indexOf(Math.min.apply(null, ds))];
};
> difference(1, 355)
6
> closest(1, [10, 90, 200, 280, 355])
355
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With