Skip to content Skip to sidebar Skip to footer

Get JSON Data Where Value Is Nearest To Number X

I have a user inputted number, X. Along with a list of data in JSON format. **114** 80 145 175 240 320 **123** 85 155 190 260 345 **132** 90 170 2

Solution 1:

Try something like this:

var data = [{"Body Weight":114," Untrained": 80," Novice": 145," Intermediate": 175," Advanced": 240," Elite": 320},
            {"Body Weight":123," Untrained": 85," Novice": 155," Intermediate": 190," Advanced": 260," Elite": 345},
            {"Body Weight":132," Untrained": 90," Novice": 170," Intermediate": 205," Advanced": 280," Elite": 370}];

var x = 140,
    difference = 0,
    bestIndex = 0,
    bestDifference = Infinity,
    i, cur, bodyWeight;

for (i = 0; i < data.length; i++) {
    cur = data[i];
    bodyWeight = cur["Body Weight"];
    difference = Math.abs(x - bodyWeight);
    if (difference < bestDifference) {
        bestDifference = difference;
        bestIndex = i;
    }
}

console.log(data[bestIndex]);

DEMO: http://jsfiddle.net/wuSux/2/

Change the value of x to find the closest to that number.


Solution 2:

Change your data so the last Body Weight is 320 instead of "320+", then:

function getClosest(x) {
    for (var i = data.length - 1; i > -1; i--) {
        if (x > data[i]["Body Weight"]) break
    }
    if (i === data.length - 1) return data[i];
    if (i === -1) return data[0];

    return data[i + +(x > ((data[i]["Body Weight"] + data[i + 1]["Body Weight"]) / 2))];
}

DEMO: http://jsfiddle.net/s8Xge/


Or if you prefer:

function getClosest(x) {
    for (var i = data.length - 1; i > -1; i--) {
        if (x > data[i]["Body Weight"]) break
    }
    return i === data.length - 1                                     ? data[i] :
           i === -1                                                  ? data[0] :
           (data[i]["Body Weight"] + data[i + 1]["Body Weight"]) / 2 ? data[i + 1] :
                                                                       data[i];
}

Post a Comment for "Get JSON Data Where Value Is Nearest To Number X"