Last active
October 7, 2015 08:38
-
-
Save alloyking/3136288 to your computer and use it in GitHub Desktop.
Find Closest Number Match in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var numberArray = [1,3,6,15,25,50]; | |
var testValue = 19; | |
var fn = closestMatch(numberArray, testValue); | |
alert(fn); | |
function closestMatch(numbers, value){ | |
var closestValue, smallestDiff, absoluteDiff | |
var len = numbers.length; | |
closestValue = smallestDiff = 99999; | |
for (var i = 0; i < len; ++i) | |
{ | |
absoluteDiff = numbers[i] - value; | |
absoluteDiff = (absoluteDiff < 0)? -absoluteDiff: absoluteDiff; //Math.abs | |
if (absoluteDiff < smallestDiff ) | |
{ | |
smallestDiff = absoluteDiff | |
closestValue = numbers[i]; | |
} | |
} | |
return closestValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment