如何从一组特定的数字中找到最接近的数字:javascript

时间:2016-03-07 06:35:29

标签: javascript object numbers

我有一组数字&我的要求是找到与特定变量相同或最接近的数字 设置/数字对象

var person = {
    A:107,
    B:112,
    C:117,
    D:127,
    E:132,
    F:140,
    G:117,
    H:127,
    I:132,
    J:132,
    K:140,
    L:147,
    M:117,
    N:127,
    O:132
};

我需要找到一个最接近的更高的数字到vaiable x
eg1-如果

x = 116;

那么从数字集合到x的最接近的数字是117,其在C,G,M处重复 所以我需要用javascript

以编程方式找出C,G,M

eg2-

x= 127

然后从D,H,N处的数字集重复x到相同的数字 所以我需要用javascript以编程方式找出D,H,N

感谢您的帮助

10 个答案:

答案 0 :(得分:3)

您可以使用 reduce 查找最低差异并使用该值收集密钥。如果找到较低的差异,则将密钥数组替换为新的较低密钥集,例如

function getNextHighest(obj, value) {
  var diff = Infinity;
  return Object.keys(obj).reduce(function(acc, key) {
    var d = obj[key] - value; 
    if (d > 0 && d < diff) {
	  diff = d;
	  acc = [key];
	} else if (d == diff) {
	  acc.push(key)
	}
	return acc;
  }, [])
}

var person = {A:107,B:112,C:117,D:127,E:132,F:140,G:117,
              H:127,I:132,J:132,K:140,L:147,M:117,N:127,O:132
             };

document.write(getNextHighest(person, 116));
document.write('<br>' + getNextHighest(person, 140));

答案 1 :(得分:0)

您可以尝试这样的事情:

注意,如果您只想要密钥,可以将result[k] = obj[k];替换为result.push(k)并将结果设为数组。

var person = {A:107,B:112,C:117,D:127,E:132,F:140,G:117,H:127,I:132,J:132,K:140,L:147,M:117,N:127,O:132};

function searchNearestNum(obj, x){
  var value = null;
  var result = {};
  
  Object.keys(obj).sort(function(a,b){
  	return obj[a]>obj[b]?1:(obj[a]<obj[b])?-1:0
  }).forEach(function(k){
    if(!value && obj[k]>x){
      value = obj[k];
      result[k] = obj[k];
    }
    else if(obj[k] === value){
      result[k] = obj[k];
    }
  });
  
  return result;
}

function getList(){
  var searchValue = document.getElementById("txt").value;
  if(searchValue && !isNaN(searchValue)){
    searchValue = parseInt(searchValue);
    print(searchNearestNum(person, searchValue));
  }
}

function print(obj){
  document.getElementById("result").innerHTML = "<pre>" + JSON.stringify(obj,0,4) + "</pre>";
}
<input id="txt"/>
<button onclick="getList()">get list</button>

<p id="result"></p>

答案 2 :(得分:0)

完全编辑以满足我的评论者=)

var x = 116;

var max = x;

for (var key in person) {
  if(person[key]>max){
    max = person[key];
  }
}

function nextMax(ar, k, m) {
    var dif = m; //Some high number
    var rkey = null;
    for (var key in ar) {
        var check = ar[key]-k;
        if(check<dif && check > 0){
          dif = check;
          rkey = key;
        }
    }
    return(rkey);
}

var keys = [];
var values = [];
for(var ckey; ckey = nextMax(person, x, max); ){
    if(ckey == null){
    break;
  }
  keys.push(ckey);
  values.push(person[ckey]);
  x = person[ckey];
}

console.log(keys);
console.log(values);

检查它是否有效:https://jsfiddle.net/Aschab/q65wes0a/2/

答案 3 :(得分:0)

方法1

尝试非常简单的算法

demo

第一步 - &gt;将数组中的值推送为[键,值,值与搜索之间的差异]

var personArray = [];
for ( var key in person )
{
  if ( ( person[key] - 116 ) > 0 )
  {
     personArray.push([key, person[key], person[key] - 116  ]);
  }
}

最后一步 - &gt;按差异值

对其进行排序
personArray.sort( function(a,b){return a[2]-b[2]} );
console.log( personArray[0][1] );

方法2

为了使它更简单,保持差异最小的句柄

var personArray = [];
var lowestDifference = 0;
var nearestHigherValue = 0;
for ( var key in person )
{
  var difference = person[key] - 116;
  if ( difference > 0 && lowestDifference < difference )
  {
     lowestDifference = difference;
     nearestHigherValue = person[key] ;
  }
}
console.log("nearest higher value is " + nearestHigherValue );

答案 4 :(得分:0)

我认为这应该有用

var resultObject = [];

function search(x, person){
    for (var i=0; i < person.length; i++) {
        if ((person[i].name === x) || (person[i].name === (x+i))) {
            return person[i];
        }
    }
}

var result = search(x, person);
resultObject.push(result);
var x = resultObject.length;
while(x >0){
   console.log(x+"\n");x--;
}

答案 5 :(得分:0)

您可以使用以下功能:

function findNearestNumbers(x, person) {
  var results = [];
  var currentClosest;

  // Difference function measures the difference
  // between two numbers
  var diff = function(a, b) {
    return Math.abs(a - b);
  }

  // Loop through each number on the person
  for(var i in person) {

    // We don't even need to do the diff if x is greater
    // than the current number
    if(x > p[i]) {
      continue;
    }

    // Calculate the differnce between the current
    // Number and the supplied 'x' value
    var d = diff(x, person[i]);

    // We want the highest number, not a matching number.
    if(diff === 0) {
       continue;
    }

    if(!currentClosest || d < currentClosest) {

      // If it's the closest number so far, create
      // a new array to store the results, with this key as
      // the first element
      results = [i];
      currentClosest = d;
    }
    else if(currentClosest === d) {

      // If this is number is the same as the closest number
      // then add this key to the results array
      results.push(i);
    }
  }

  return results;
}

在这里试试小提琴https://jsfiddle.net/y4nu3t0d/4/

答案 6 :(得分:0)

尝试使用for..in循环,Object.keys()Array.prototype.map()Array.prototype.reduce()person的值存储为新对象的属性键。如果property不存在,则添加person的属性,否则在创建的对象中连接person的属性;通过比较数字来过滤属性;返回包含原始对象属性的连接字符串,其中筛选的数字大于输入参数编号

var person = {
  A: 107, B: 112, C: 117, D: 127, E: 132,
  F: 140, G: 117, H: 127, I: 132, J: 132,
  K: 140, L: 147, M: 117, N: 127, O: 132
};

var res = function(n) {
  var data = {};
  for (var prop in person) data[person[prop]] = (data[person[prop]] || "") + prop;
  return data[Object.keys(data).map(Number).reduce(function(a, b) {
    return a > n ? a : b
  })];
}

document.body.textContent = res(116) + "\n" + res(140)

答案 7 :(得分:0)

在对象上尝试一系列sortfilter

var person = {
  A: 107,
  B: 112,
  C: 117,
  D: 127,
  E: 132,
  F: 140,
  G: 117,
  H: 127,
  I: 132,
  J: 132,
  K: 140,
  L: 147,
  M: 117,
  N: 127,
  O: 132
};

var myNum = 117;

var nearest = Object.keys(person)
.sort(function(item1, item2) {
    if (person[item1] > person[item2]) {return 1};
    if (person[item1] < person[item2]) {return -1};
   return 0;
}).filter(function(item) {
  return person[item] >= myNum;
}).filter(function(item, index, list){
  return person[list[0]] == person[item];
});

console.log(nearest) // will print ["C","M","G"]

查看此fiddle以获取完整示例。

答案 8 :(得分:0)

这是一个直接的方法,有一个Array#forEach循环和一个变量用于保持delta和一个用于键。

&#13;
&#13;
function nearestHigher(object, v) {
    var delta = -1,
        keys = [];
    Object.keys(object).forEach(function (k) {
        var d = object[k] - v;
        if (d > 0) {
            if (!~delta || d < delta) {
                delta = d;
                keys = [k];
                return;
            }
            d === delta && keys.push(k);
        }
    });
    return keys;
}

var person = { A: 107, B: 112, C: 117, D: 127, E: 132, F: 140, G: 117, H: 127, I: 132, J: 132, K: 140, L: 147, M: 117, N: 127, O: 132 };

document.write('<pre>' + JSON.stringify(nearestHigher(person, 116), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(nearestHigher(person, 132), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(nearestHigher(person, 140), 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 9 :(得分:-1)

试试这个

function getNearest(x){
   var keys=[];
   for(var key in person){
     if(person[key]==x+1)
        keys.push(key)
   }
   return keys;
}
getNearest(116)