Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a number to closest number in a set in Javascript

I have an array of values, and I need a function that takes in two integers, and assigns those two integers to their closest values from the array.

var bandwidthSteps = [0.128, 0.256, 0.512, 1, 2, 4, 5, 8, 10, 12, 15, 18, 20, 22, 25, 30, 40, 50, 55, 60, 80, 90, 100, 110, 128, 200, 256, 300, 350, 400, 450, 500];

When a "private" value and a "guest" value come in, I need to match each to their closest value in the set - rounded down.

var function = closestValues(private,guest) {
    //
};

So when this function is given 14 and 21, I need the function to return:

private = 15
guest = 20

since those are the closest matches to integers in the array. Note that the "steps" in the array are irregular, it's not like 2, 5, 8, 11. Or else it would be easy.

The solution in a JS function would be great, or the correct direction to go in making such a function. The ideas that come to me seem overly complex: for each set of two consecutive numbers in the array, average the two and then determine if the given integer is greater or less than the average, etc etc. I'm sure there is a more concise way.

like image 715
SpaceNinja Avatar asked Jan 04 '23 22:01

SpaceNinja


1 Answers

You could iterate the array and check with the absolute delta and the last delta.

function closestValue(v) {
    var value,
        lastDelta;

    bandwidthSteps.some(function (a) {
        var delta = Math.abs(v - a);
        if (delta >= lastDelta) {
            return true;
        }
        value = a;
        lastDelta = delta;
    });
    return value;
}

var bandwidthSteps = [0.128, 0.256, 0.512, 1, 2, 4, 5, 8, 10, 12, 15, 18, 20, 22, 25, 30, 40, 50, 55, 60, 80, 90, 100, 110, 128, 200, 256, 300, 350, 400, 450, 500];

console.log(closestValue(14));
console.log(closestValue(21));
like image 157
Nina Scholz Avatar answered Jan 07 '23 22:01

Nina Scholz