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?

2
  • stackoverflow.com/questions/27376295/… Commented May 23, 2016 at 6: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 Commented May 23, 2016 at 6:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.