我想测试一些输入字段中具有最接近最高值['size']
的累积值(var goal
)数组。
假设我的目标是找到最接近 size 95
的值。
var variants = [
{ value: "128428226", size: "50 ", price: 3.72, priceIncl: 4.5 },
{ value: "128428229", size: "100 ", price: 5.5, priceIncl: 6.65 },
{ value: "128428232", size: "150 ", price: 7.27, priceIncl: 8.8 }
]
var goal = 95;
var closest = variants;
var closestPrice = '';
var closestPriceIncl = '';
var closestVal = '';
$.each(variants, function(){
if (closest['size'] == null || Math.abs(this['size'] - goal) < Math.abs(closest['size'] - goal)) {
closest = this;
closestPrice = closest['price'];
closestPriceIncl = closest['priceIncl'];
closestVal = closest['value']
}
});
我能够获得我想要的所有值。但是,当目标类似于 75
时,我的脚本会从 size: "50"
中选择值。所以实际上当目标是 51 时,它应该选择 100 等等。
我真的找不到办法做到这一点。我找到了一些其他使用函数的答案,但后来我不知道如何获得其他值。 (只是我需要找到最接近的最高值。) 非常感谢任何帮助。
最佳答案
如果我正确理解你的问题,下面的代码应该足够了:
var variants = [
{ value: "128428226", size: "50 ", price: 3.72, priceIncl: 4.5 },
{ value: "128428229", size: "100 ", price: 5.5, priceIncl: 6.65 },
{ value: "128428232", size: "150 ", price: 7.27, priceIncl: 8.8 }
];
var goal = 51;
var closest = null ;
var minDiff = Number.MAX_SAFE_INTEGER;
for(var index in variants){
var valueObject = variants[index];
if(valueObject.size > goal){
var diff = Math.abs(valueObject.size - goal);
if(diff < minDiff){
closest = valueObject;
minDiff = diff;
}
}
}
console.log(minDiff);
console.log(closest);
两个定义谓词是最接近的变体的大小大于目标,并且大小之间的差异应该最小。
关于javascript - 多列数组中最接近的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054025/