如何从一组特定数字中找到最近的更高数字:javascript [英] How to find a nearest higher number from a specific set of numbers :javascript

查看:51
本文介绍了如何从一组特定数字中找到最近的更高数字:javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a set of numbers & my requirements is to find same or nearest higher number to a specific variable set/object of 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
};

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

I need to find a nearest higher number to vaiable x
eg1- if

x = 116;

然后从数字集中到 x 最接近的更高数字是 117,它在 C、G、M 处重复所以我需要用 javascript 以编程方式找出 C、G、M

then nearest higher number to x from number set is 117, which repeat at C, G, M so I need to find out C, G, M programatically with javascript

eg2-

x= 127

然后在 D、H、N 处重复与数字组中的 x 相同的数字所以我需要用javascript以编程方式找出D、H、N

then same number to x from number set repeat at D,H,N so I need to find out D,H,N programatically with javascript

感谢帮助

推荐答案

您可以使用 reduce 找到最小的差异并收集具有该值的键.如果找到较低的差异,则键数组将替换为新的较低键集,例如

You can use reduce to find the lowest difference and collect the keys with that value. If a lower difference is found, the keys array is replaced with the new set of lower keys, e.g.

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));

这篇关于如何从一组特定数字中找到最近的更高数字:javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆