I\'m looking for a really quick, clean and efficient way to get the max \"y\" value in the following JSON slice:
[
{
\"x\": \"8/11/2009\",
\"y\": 0
Well, first you should parse the JSON string, so that you can easily access it's members:
var arr = $.parseJSON(str);
Use the map
method to extract the values:
arr = $.map(arr, function(o){ return o.y; });
Then you can use the array in the max
method:
var highest = Math.max.apply(this,arr);
Or as a one-liner:
var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));
One way would be to use Array reduce..
const max = data.reduce(function(prev, current) {
return (prev.y > current.y) ? prev : current
}) //returns object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce (IE9 and above)
If you don't need to support IE (only Edge), or can use a pre-compiler such as Babel you could use the more terse syntax.
const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
Here is the shortest solution (One Liner) ES6:
Math.max(...values.map(o => o.y));
Each array and get max value with Math.
data.reduce((max, b) => Math.max(max, b.costo), data[0].costo);
// Here is very simple way to go:
// Your DataSet.
let numberArray = [
{
"x": "8/11/2009",
"y": 0.026572007
},
{
"x": "8/12/2009",
"y": 0.025057454
},
{
"x": "8/13/2009",
"y": 0.024530916
},
{
"x": "8/14/2009",
"y": 0.031004457
}
]
// 1. First create Array, containing all the value of Y
let result = numberArray.map((y) => y)
console.log(result) // >> [0.026572007,0.025057454,0.024530916,0.031004457]
// 2.
let maxValue = Math.max.apply(null, result)
console.log(maxValue) // >> 0.031004457
clean and simple ES6 (Babel)
const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);
The second parameter should ensure a default value if arrayToSearchIn
is empty.