0

I have several variables with some values assigned. For ex:

Gain_weight = 0.01 Gain_weather = 0.02

and some more like this. Now I want to get the variable name with highest value assigned.

When I do something like this It returns the value not the name.

var rootNode = Math.max(Gain_weight,Gain_smoking,Gain_exercising,Gain_foodhabits,Gain_parent_heartattack,
            Gain_alcohol,Gain_occupation,Gain_workinghrs);

So instead of value how can I get the highest value assigned string?

CraZyDroiD
  • 6,622
  • 30
  • 95
  • 182
  • http://stackoverflow.com/questions/27376295/getting-key-with-the-highest-value-from-object – apieceofbart May 23 '16 at 06:38
  • Why do you need this, what is the use case? It isn't possible to programmatically obtain a variable name in the manner you suggest here – nem035 May 23 '16 at 06:44

1 Answers1

1

After checking this question it seems it may not be possible to get the name.

A way around can be either using an object or a associate array with name as same of variable name and it's value as the variable value

Hope this snippet will help to understand

// Array with name value pair
var _myDemoArray = [
{name:'Gain_weight',
 value:0.01},
{name:'Gain_weather',
value:0.02}]

 // sort the array in descending order to get the element with maximum value. 
var _getSortedElem = _myDemoArray.sort(function(a,b){
  return b.value -a.value;
});
// The first element of this sorted array will have element with maximum value
console.log(_getSortedElem[0].name);

Check this jsfiddle for demo

Community
  • 1
  • 1
brk
  • 48,835
  • 10
  • 56
  • 78