CraZyDroiD CraZyDroiD - 6 months ago 19
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,
Gain_alcohol,Gain_occupation,Gain_workinghrs);


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

Answer

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

Comments