javascript - Get max or min value from associative array with function and parameters -


here code far got right now:

<!doctype html> <html> <body>  <button onclick="scanarray('a', 'max')">test a, max</button>  <button onclick="scanarray('b', 'min')">test b, min</button>    <p id="demo">test</p>  <script>    var array = [{"a":1},{"b":3},{"a":6},{"b":10}];   var max = null; var min = null; var value = null;  function scanarray(scanval, searchterm) {    if (array.length < 1) {     return -1;   }      if(searchterm == "max"){      max = math.max.apply(math,array.map(function(e){return e.scanvalue;}))      }else if (searchterm == "min"){      min = math.min.apply(math,array.map(function(e){return e.scanval;}))  }else {document.getelementbyid("demo").innerhtml = "only max , min available";}      if(searchterm == "max"){          document.getelementbyid("demo").innerhtml = "search: " + scanval +"  "+ "value: " + max;     }      if(searchterm == "min"){         document.getelementbyid("demo").innerhtml = "search: " + scanval +"   "+ "value: " + min;     }  } </script>  </body> </html> 

the above should give me , 6 or b , 3 results. nan result value part. when using "return e.a" in math section , having keys works.

i want able determin max or min value of key enter parameter function.

hope can me here.

thanks in advance.

thevagabond

there naming mess in code. example scanvalue name of function trying reach parameter of e(e.scanvalue). should scanval. still there problems. can't reach property "a" or "b" of e if e.scanval. you're trying reach variable of variable.

then, should use e[scanval]. returns value of "a" or "b". if object doesn't have 1 of them? should add "|| 0" correct value. (instead of nan or undefined) it means that; use e[scanval] if valid, if not use 0.

use this;

return e[scanval] || 0; 

if boundaries include negative values, use -9999 or -infinity.


Comments