Created
          September 13, 2013 15:42 
        
      - 
      
- 
        Save vipickering/6552366 to your computer and use it in GitHub Desktop. 
    Javascript: Find The Closest Number In Array To A Specific Value
  
        
  
    
      This file contains hidden or 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 array = []; | |
| function closest(array,num){ | |
| var i=0; | |
| var minDiff=1000; | |
| var ans; | |
| for(i in array){ | |
| var m=Math.abs(num-array[i]); | |
| if(m<minDiff){ | |
| minDiff=m; | |
| ans=array[i]; | |
| } | |
| } | |
| return ans; | |
| } | |
| /*call array name and desired value to be closet */ | |
| alert(closest(array,88)); | 
I came up with this ...
const nearest = (arr) => val => arr.reduce((p,n) => Math.abs(p) > Math.abs(n-val) ? n-val : p, Infinity) + val;
let num = 5;
let arr =[1,2,3,4,5,6,7,8,9,10];
const result = arr.reduce((prev, curr) => Math.abs(curr - num) < Math.abs(prev - num) ? curr : prev);
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Thanks.