[英]Find the closest smaller value of an array
我想我想要的很简单,但我真的找不到正确的解决方案。
我在 Javascript 中有这种数组:
[0, 38, 136, 202, 261, 399]
单击按钮时,我会得到一个从 0 到 600 的生成值。 我需要的是在这个数组中找到最近的较低值。
比如生成的值为198,我想得到136作为结果。 如果生成的值是 300,我想要 261……如果是 589,我想要 399 等等。
到目前为止,我已经尝试过使用以下代码:
var theArray = [ 1, 3, 8, 10, 13 ];
var goal = 7;
var closest = null;
$.each(theArray, function(){
if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) {
closest = this;
}
});
alert(closest);
但它只返回最接近的值......现在我只需要为给定数字获得最接近的较小值......我如何改进我的算法以满足我的需求?
谢谢!
反转数组并使用find
let arr = [0, 38, 136, 202, 261, 399]; let val = 300; let number = arr.reverse().find(e => e <= val); console.log(number);
如果您的数组已排序,并且足够小,那么一个非常简单的模式可以执行您想要的操作,它只是简单地遍历数组,直到number > number-in-array
然后返回前一个位置的数字。
function getClosestValue(myArray, myValue){
//optional
var i = 0;
while(myArray[++i] < myValue);
return myArray[--i];
}
问候。
另一种解决方案是过滤数组以找到最接近的较小值,然后将Math.max()
函数与扩展运算符一起使用:
// Array to select value
let array = [0, 38, 136, 202, 261, 399];
// Random value
let random = 168;
// Filtering array with closest smaller values [0, 38, 136]
let filtered = array.filter(num => num <= random);
// The closest value will be the maximum
let closest = Math.max(...filtered);
在一行代码中:
let closest = Math.max(...array.filter(num => num <= random));
您可以使用Array#some
并在项目大于或等于所需值时退出。 否则将实际值分配为返回值。
这个提议适用于排序数组。
function getClosest(array, value) { var closest; array.some(function (a) { if (a >= value) { return true; } closest = a; }); return closest; } var array = [0, 38, 136, 202, 261, 399]; console.log(getClosest(array, 100)); // 38 console.log(getClosest(array, 198)); // 136 console.log(getClosest(array, 300)); // 261 console.log(getClosest(array, 589)); // 399
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.