JSFiddle - React, Tailwind, and code Playground
by joecritch
JavaScript
// 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.
var angles = [130, -240, 600, 5, -140, 15]
var getClosest = function(angle) {
var anglesWithDifferences = _.map(angles, function(v) { return [v, Math.abs(v - angle)]; });
var sortedAngles = _.reduce(anglesWithDifferences, function(memo, val) {
return (memo[1] < val[1]) ? memo : val;
}, [-1, 999]);
return [sortedAngles[0], sortedAngles[1]];
};
var res = getClosest(100);
document.write('nearest: ' + res[0]);
document.write('next nearest : ' + res[1]);