I have below array
const floorPerDayMilestones = [25, 50, 75, 100, 125, 150, 175, 200]
From the frontEnd user enters any number say it is
const number = 136
I need to find closest to the number but the lesser one.
So the output should be 125
Even if the number is 149
the output should be 125
How can I do this. I tried many way but could get the answer.
Thanks!!!
If it's sorted in ascending order like in the question this should work.
const floorPerDayMilestones = [25, 50, 75, 100, 125, 150, 175, 200];
const number = 136;
function findClosest(arr, num) {
for (let i = 0; i < arr.length; ++i) {
if (arr[i] > num) {
return arr[i - 1];
}
}
}
console.log(findClosest(floorPerDayMilestones,number));