Skip to content Skip to sidebar Skip to footer

How To Get Math.min() To Return The Variable Name Instead Of A Number

I have five variables - organism.one, organism.two, and so on, up to five. They're all equal to random numbers. I'm trying to find the smallest of them, which I can do with Math.m

Solution 1:

My suggestion is use [].reduce

var objects = [{
    name: 'one',
  val: 13
},
{
    name: 'two',
  val: 12
},
{
    name: 'three',
  val: 11
}];

var minimum = objects.reduce(function(obj1, obj2){ 
  return (obj1.val < obj2.val) ? obj1: obj2;        
});

console.log(minimum.val)

Solution 2:

Since you have an object with keys that contain numbers, you can use for ... in to iterate through them to find the smallest key:

var organism = {
      one: 50,
      two: 100,
      three: 25,
      four: 15,
      five: 999
    },
    min = Infinity,
    key;
  
for(var i in organism) {
  if(organism[i] < min) {
    min = organism[i];
    key = i;
  }
}

console.log(key); //four

Solution 3:

This should do it:

var lowestValsKey;
for(var key in organism){
    if(!lowestValsKey){
        lowestValsKey = key;
    }
    if(organism[key] < organism[lowestValsKey]){
        lowestValsKey = key;
    } 
}

console.log(lowestValsKey);

Solution 4:

No need for all these different functions, You're very close, you just need one loop to do it:

After you get the min, loop through the object to find a match:

JSBin Example

var organism = {
  two: 2,
  three: 3,
  four: 4,
  one: 1, 
  five: 5
};

var runt = Math.min(organism.one, organism.two, organism.three, organism.four, organism.five);

var lowest;
for (var org in organism) {
  if (organism[org] === runt) {
    lowest = org;
  }
}

Solution 5:

As you've noticed, Math.min only takes parameters and only returns a single number. There is no way to make it do what you are asking for it to do.

However, if I am reading your question correctly, what you are really asking is:

Can I pass an object to a function and get the key name of the lowest value?

If so, there is a way to do that.

var organism = {
  one: 12,
  two: 19,
  three: -1,
  four: 99,
  five: 6
};

functionfindSmallestKey(obj) {
  var smallestKey;
  var smallestValue = Number.MAX_VALUE;

  Object.keys(obj).forEach((key) => {
    var val = obj[key];
    
    if (val < smallestValue) {
       smallestValue = val;
      smallestKey = key;
    }   

  });
  
  return smallestKey;
}

var k = findSmallestKey(organism);

console.log('Smallest key is ', k);

Post a Comment for "How To Get Math.min() To Return The Variable Name Instead Of A Number"