我有一个用户输入的数字X.以及JSON格式的数据列表。获取JSON数据,其中值最接近数字X
**114** 80 145 175 240 320
**123** 85 155 190 260 345
**132** 90 170 205 280 370
我想将X与第一列中的最接近的数字匹配,然后在该行中返回以下值。
不知道我是否以最好的方式格式化了JSON。但这里是我到目前为止有:http://jsfiddle.net/wuSux/
我有一个用户输入的数字X.以及JSON格式的数据列表。获取JSON数据,其中值最接近数字X
**114** 80 145 175 240 320
**123** 85 155 190 260 345
**132** 90 170 205 280 370
我想将X与第一列中的最接近的数字匹配,然后在该行中返回以下值。
不知道我是否以最好的方式格式化了JSON。但这里是我到目前为止有:http://jsfiddle.net/wuSux/
尝试这样:
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/
变化x
值找到最接近号码。
更改您的数据,所以最后Body Weight
是320
代替"320+"
,则:
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/
或者如果你喜欢:
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];
}
你如何定义最近?我建议你查看lodash.com或underscore.org库。他们有很多方法来排序,分组和查找值。 – lucuma 2013-04-25 19:36:50
是否有可能让JSON数据按第一列的值进行预先排序?这将使您能够进行二进制搜索,这将是最有效的。 – 2013-04-25 19:36:51