CraZyDroiD CraZyDroiD - 2 years ago 96
AngularJS Question

Angularjs getting variable name with highest value

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,

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

Answer Source

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 = [

 // 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

Check this jsfiddle for demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download