0

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 paymentMilestones indexes the daysOverdue var is closest to? I need that value returned, so in this case the function should return 30.

Brandon Durham
  • 7,096
  • 13
  • 64
  • 101
  • True! I think this example doesn't account for ties and also uses jquery instead of plain javascript. Check my simple solution :) – Michail Michailidis Oct 17 '14 at 16:41
  • Check my update - I believe that this addition if it is correct will stop the loop if the minDelta starts becoming bigger again and it will return the previous element – Michail Michailidis Oct 20 '14 at 17:12

1 Answers1

0

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);
Michail Michailidis
  • 11,792
  • 6
  • 63
  • 106