最接近数组的价格
Price closest to in array?
在Javascript中这三个数组中,数组中的值是ProductId => Price (xx:xx)
var instantPriser = {11: 48,12: 96,13: 144,14: 192,15: 240,16: 288,17: 336,18: 384,19: 432,20: 480,21: 528,22: 576,23: 624,24: 672,25: 720,26: 768,9999999999999999};
var maletPriser = {27: 20,28: 40,29: 60,30: 80,31: 100,32: 120,33: 140,34: 160,35: 180,36: 200,37: 220,38: 240,39: 260,40: 280,41: 300,42: 320,43: 340,44: 360,45: 380,46: 400,47: 420,48: 440,49: 460,50: 480,51: 500,52: 520,53: 540,54: 560,55: 580,56: 600,57: 620,58: 640,59: 660,60: 680,61: 700,62: 720,63: 740,64: 760,65: 780,66: 800,67: 820,68: 840,69: 860,70: 880,71: 900,9999999999999999};
var heleBoenner = {72: 89,73: 178,74: 267,75: 356,76: 445,77: 534,78: 623,79: 712,80: 801,81: 890,82: 979,83: 1068,84: 1157,85: 1246,86: 1335,87: 1424,88: 1513,89: 1602,90: 1691,91: 1780,92: 1869,93: 1958,94: 2047,95: 2136,9999999999999999};
我想看看如何通过我的价格从数组中获得最接近的"productId"?
我试过了,但似乎效果不太好:
var price = 450;
for ( i=0;i<instantPriser.length;i++ ){
if ( pris <= instantPriser[i]){
alert(instantPriser[i]);
return false;
}
}
应该输出19或20,因为值是432和480(最接近450)
我该怎么做?
将所有值放入数组中,然后使用以下代码查找最接近的值
var closest = null;
$.each(arr, function(index,value1){
if (closest == null || Math.abs(value1 - value) < Math.abs(closest - value)) {
closest = this.value;
}
});
alert(closest );
不需要任何库也可以这样做
findClosest=function (obj,price) {
var pid;
var min = 100000
for(i in obj) {
if(obj.hasOwnProperty(i) {
var diff = Math.abs(price - obj[i]);
if(min >= diff) {
min = diff
pid = i;
}
}
}
console.log(pid); // replace it with return or alert
// or whatever your logic is
}
使用findClosest(instantPricer,450)
函数式:
var target = 450;
Object.keys(instantPriser).reduce(function(best, x) {
return Math.abs(instantPriser[best] - target) <= Math.abs(instantPriser[x] - target)
? best : x;
})
或使用辅助函数:
Array.prototype.min = function(arr, f) {
f = f || function(x) { return x; };
return arr.reduce(function(best, x) { return f(best) <= f(x) ? best : x; });
}
给:var target = 450;
Object.keys(instantPriser).min(function(x) {
return Math.abs(instantPriser[key] - target);
})
相关文章:
- 获取最接近的数组数
- JavaScript:如何在最接近值的关联数组中查找键
- 在 javascript 数组中搜索最接近的下一个值
- 按键查找数组中最接近的 2 个元素
- 检测数组中接近且具有相同索引值的数字
- Javascript/jquery- 如何在数组中获取最接近的时间
- 从数组中获取最接近的数字匹配项,必须更低
- 如何使用 lodash 从数组中获取最接近目标的前两个数字
- javascript/查找数组中最接近的值
- 我的算法中查找数组最大元素的缺陷在哪里
- 在Javascript中查找最接近所需值的数组条目
- 查找最接近给定时间数组的时间
- Javascript在数组中找到最接近的数字,而不需要重复
- 从数组中获取最接近的数字
- Javascript在数组中找到最接近的数字
- 最接近数组的价格
- 如何从数组中获得最接近的值
- 我如何在数组中找到最接近的数字,而不用遍历
- 获取数组(JS)组合的最接近的值
- 改变这种字符串数组最优雅的方法是什么