简体   繁体   中英

Round off number to the nearest Highest number from array in Javascript

I have a requirement where I have an array of number and I also get a new number after some calculation. After getting that new number I need to round it off to the nearest highest value from the array. For eg:

var counts = [2,33,61,92,125,153,184,215,245,278,306,335,365]

So if the new number is 35 then it should check from the array and display number 61 and not 33. It should always round off to the highest number from the array.

I tried this but it only returned me the nearest value from the array and not the highest number from the array. May I know where did I go wrong or what extra needs check needs to be done?

var counts = [2,33,61,92,125,153,184,215,245,278,306,335,365],
  goal = 35;

var closest = counts.reduce(function(prev, curr) {
  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});

console.log(closest);

Use .find()

Be sure your array is sorted or this will give you a wrong answer.

 var counts = [2,33,61,92,125,153,184,215,245,278,306,335,365] var goal = 33; var closest = counts.find(numb => numb >= goal); console.log(closest);

The following return the min value among all values in counts greater than goal.

 var counts = [2,33,61,92,125,153,184,215,245,278,306,335,365], goal = 35; let min = Math.min(...counts.filter( num => num >= goal )); console.log(min)

Try this code. It will work for both sorted and unsorted arrays.

 let countsArr = [2,36,61,92,125,153,184,215,245,278,306,335,365]; const goalValue = 35; let diff = Number.MAX_VALUE; const closestMax = countsArr.reduce((acc, curr) => { const currDiff = curr - goalValue; if((currDiff > diff) || (currDiff < 0)) { return acc; } else { diff = currDiff; return curr; } }); console.log(closestMax);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM