我在json中有以下对象数组,我想得到数组中对象的索引,该索引最接近给定数字值的天数属性。
在jQuery或JS中存在任何内置函数,或者我如何轻松解决它?
感谢您的帮助。
"warningAttributes": [
{
"id": "3",
"days": 15,
"color": "#FFFFFF"
},
{
"id": "4",
"days": 98,
"color": "#343434"
}
]
答案 0 :(得分:6)
var warningAttributes = [{"id": "3", "days": 15, "color": "#FFFFFF"},
{"id": "4", "days": 98, "color": "#343434"}]
var target = 90;
var nearest = warningAttributes.sort(function(a,b){
return Math.abs(a.days-target) - Math.abs(b.days-target)
})[0];
如果您不在[0]
答案 1 :(得分:0)
考虑到您正在尝试找到最接近的ID。
你可以这样做,http://jsfiddle.net/s4jq5kv7/。虽然你需要清理代码,但这是有效的。
var id=3;
var temp;
var prev;
var x={"warningAttributes": [
{
"id": "3",
"days": 15,
"color": "#FFFFFF"
},
{
"id": "4",
"days": 98,
"color": "#343434"
}
]
}
prev=x.warningAttributes[0].id;
val=prev;
$(x.warningAttributes).each(function(i,ele){
if(id>parseInt(ele.id)){
temp=id-parseInt(ele.id);
}else{
temp=parseInt(ele.id)-id;
}
if(prev>temp)
{prev=temp;
val=ele.id;}
})
console.log(val)
唯一的问题是,如果有一个数字与两个以上的数字有相同的差异,那么返回第一个数字。
前3
和4
,如果您发现最接近3.5
,则会获得第一个数字,即3
。
答案 2 :(得分:0)
如果我理解得很好:
jQuery(document).ready(function () {
var control=40;
var json = {"warningAttributes": [
{
"id": "3",
"days": 15,
"color": "#FFFFFF"
},
{
"id": "4",
"days": 98,
"color": "#343434"
},
{
"id": "5",
"days": 40,
"color": "#343434"
}
]};
$.each(json.warningAttributes, function(k, v) {
var diff;
diff= control - v.days
if(diff==0) alert("this is your element: " + v.id);
})
});
答案 3 :(得分:0)
这很简单:
function getNearest(arr,value)
{
var diff = null;
var index= 0;
$.each(arr,function(i,item) {
var current = Math.abs(item.days - value);
if (diff == null) diff = current;
if (current< diff)
index=i;
});
return index
}
答案 4 :(得分:0)
克里斯几乎偷了这个(+1),但这里是我如何尝试它的细分:
function getDays(arr, value) {
// get a list of the differences between the requested value
// and the numbers in the array and make them all positive
var abs = arr.map(function (el) { return Math.abs(el.days - value); });
// find the smallest number
var smallest = Math.min.apply(null, abs);
// find out where that number is in the positive number array
var index = abs.indexOf(smallest);
// return an object that contains the index of the
// object, and the number of days that were closest
return { index: index, value: arr[index].days };
}
var result = getDays(arr, 35); // Object { index: 3, value: 17 }
使用result.index
获取索引。
答案 5 :(得分:0)
我的去处是因为编写短代码很有趣。
var warningAttributes = [{"id": "3", "days": 15, "color": "#FFFFFF"},
{"id": "4", "days": 98, "color": "#343434"}]
var n = 90;
var distances = warningAttributes.map(function(c) {return Math.abs(n - c.days);})
var nearest_idx = distances.indexOf(Math.min.apply(Math, distances));