我有一个从- 1000到+ 1000的数我有一个数组,里面都是数字。是这样的:

[2, 42, 82, 122, 162, 202, 242, 282, 322, 362]

我想让我得到的数字变成数组中最接近的数字。

例如,我的数字是80,我希望它是82。


当前回答

ES6(2015年ECMAScript)版本:

Const counts = [4,9,15,6,2]; Const goal = 5; Const输出=计数。reduce((prev, curr) =>abs(curr - goal) <数学。腹肌(前一球)?Curr: prev); console.log(输出);

为了可重用性,您可以封装一个支持占位符的curry函数(http://ramdajs.com/0.19.1/docs/#curry或https://lodash.com/docs#curry)。这提供了很大的灵活性,取决于你需要什么:

const getnearest = _。Curry((计数,目标)=> { 返回计数。reduce((prev, curr) =>abs(curr - goal) <数学。腹肌(前一球)?Curr: prev); }); const closestToFive = getnearest (_, 5); const output = closestToFive([4,9,15,6,2]); console.log(输出); < script src = " https://cdn.jsdelivr.net/npm/lodash@4.17.20 lodash.min.js " > < /脚本>

其他回答

最有效的方法是二分查找。然而,即使是简单的解决方案,当下一个数字与当前数字进一步匹配时,也可以退出。这里几乎所有的解决方案都没有考虑到数组是有序的,并且迭代整个:/

const closest = (orderedArray, value, valueGetter = item => item) => orderedArray.find((item, i) => i === orderedArray.length - 1 || Math.abs(value - valueGetter(item)) < Math.abs(value - valueGetter(orderedArray[i + 1]))); var data = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]; console.log('21 -> 2', closest(data, 21) === 2); console.log('22 -> 42', closest(data, 22) === 42); // equidistant between 2 and 42, select highest console.log('23 -> 42', closest(data, 23) === 42); console.log('80 -> 82', closest(data, 80) === 82);

这也可以在非原语上运行,例如,nearest (data, 21, item => item.age)

将find更改为findIndex以返回数组中的索引。

这里的另一个变体是圆形范围,从头到脚连接,只接受给定输入的最小值。这帮助我获得了一个加密算法的字符代码值。

function closestNumberInCircularRange(codes, charCode) {
  return codes.reduce((p_code, c_code)=>{
    if(((Math.abs(p_code-charCode) > Math.abs(c_code-charCode)) || p_code > charCode) && c_code < charCode){
      return c_code;
    }else if(p_code < charCode){
      return p_code;
    }else if(p_code > charCode && c_code > charCode){
      return Math.max.apply(Math, [p_code, c_code]);
    }
    return p_code;
  });
}

我对一个类似问题的回答是考虑关系,它是在纯Javascript中,尽管它不使用二进制搜索,所以它是O(N)而不是O(logN):

var searchArray= [0, 30, 60, 90];
var element= 33;

function findClosest(array,elem){
    var minDelta = null;
    var minIndex = null;
    for (var i = 0 ; i<array.length; i++){
        var delta = Math.abs(array[i]-elem);
        if (minDelta == null || delta < minDelta){
            minDelta = delta;
            minIndex = i;
        }
        //if it is a tie return an array of both values
        else if (delta == minDelta) {
            return [array[minIndex],array[i]];
        }//if it has already found the closest value
        else {
            return array[i-1];
        }

    }
    return array[minIndex];
}
var closest = findClosest(searchArray,element);

https://stackoverflow.com/a/26429528/986160

ES6(2015年ECMAScript)版本:

Const counts = [4,9,15,6,2]; Const goal = 5; Const输出=计数。reduce((prev, curr) =>abs(curr - goal) <数学。腹肌(前一球)?Curr: prev); console.log(输出);

为了可重用性,您可以封装一个支持占位符的curry函数(http://ramdajs.com/0.19.1/docs/#curry或https://lodash.com/docs#curry)。这提供了很大的灵活性,取决于你需要什么:

const getnearest = _。Curry((计数,目标)=> { 返回计数。reduce((prev, curr) =>abs(curr - goal) <数学。腹肌(前一球)?Curr: prev); }); const closestToFive = getnearest (_, 5); const output = closestToFive([4,9,15,6,2]); console.log(输出); < script src = " https://cdn.jsdelivr.net/npm/lodash@4.17.20 lodash.min.js " > < /脚本>

我不知道我是否应该回答一个老问题,但由于这篇文章首先出现在谷歌搜索中,我希望你能原谅我在这里添加我的解决方案和我的2c。

由于懒惰,我无法相信这个问题的解决方案会是一个LOOP,所以我搜索了更多,并返回了过滤器函数:

var myArray = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
var myValue = 80;

function BiggerThan(inArray) {
  return inArray > myValue;
}

var arrBiggerElements = myArray.filter(BiggerThan);
var nextElement = Math.min.apply(null, arrBiggerElements);
alert(nextElement);

就这些!