How Can I Determine Which Array Index My Number Is Closest To?
I have an array and var that look like this: var paymentMilestones = [0, 30, 60, 90]; var daysOverdue = 33; In JavaScript, how can I programmatically determine which of the paymen
Solution 1:
A quick answer (if there is a tie it will bring back both - assuming the array is pre-sorted):
var paymentMilestones = [0, 30, 60, 90];
var daysOverdue = 33;
function findClose(array,elem){
var minDelta = null;
var minIndex = null;
for (var i = 0 ; i<array.length; i++){
var delta = Math.abs(array[i]-elem);
if (minDelta == null || delta < minDelta){
minDelta = delta;
minIndex = i;
}
else if (delta == minDelta) {
return [array[minIndex],array[i]];
}
// unchecked: stop if delta starts becoming bigger again
else {
return [array[i-1]];
}
}
return array[minIndex];
}
var closest = findClose(paymentMilestones,daysOverdue);
Post a Comment for "How Can I Determine Which Array Index My Number Is Closest To?"