How to find a nearest higher number from a specific set of numbers :javascript [duplicate]

大城市里の小女人 提交于 2019-12-13 05:25:18

问题


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

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

x = 116;

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

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

Thanks for Help


回答1:


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



回答2:


I think this should work :

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



回答3:


You can use a function like this:

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

Try the fiddle here https://jsfiddle.net/y4nu3t0d/4/




回答4:


Try a series of sort and filter on the object:

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"]

Check this fiddle for a complete example.




回答5:


Totally edited to satisfy my commenters =)

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

check it working: https://jsfiddle.net/Aschab/q65wes0a/2/




回答6:


Thi is a straight forward approach with an Array#forEach loop and a variable for keeping the delta and one for the keys.

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



回答7:


You can try something like this:

Note, if you just want keys, you can replace result[k] = obj[k]; to result.push(k) and make result an array.

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>



回答8:


Approach 1

Try this demo of a very simple algorithm

First step -> Push the values in an array as [key, value, difference between value and search]

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

Final Step -> Sort it by the difference value

personArray.sort( function(a,b){return a[2]-b[2]} );
console.log( personArray[0][1] );

Approach 2

To make it even more simpler, keep the handle of lowest difference

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



回答9:


Try utilizing for..in loop, Object.keys(), Array.prototype.map(), Array.prototype.reduce() to store values of person as property keys of new object. If property does not exist add property of person, else concatenate property of person at created object; filter properties by comparing as numbers; return concatenated string containing properties of original object where filtered number is greater than input parameter number

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)



回答10:


Try this

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


来源:https://stackoverflow.com/questions/35837589/how-to-find-a-nearest-higher-number-from-a-specific-set-of-numbers-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!