简体   繁体   中英

How to find the maximum value in JSON array which also contains some JSON array

Please find the below array JSON Object.

points:[{x:1, YValues:[34,45,56]}, {x:5, YValues:[20,12,30]}, {x:8, YValues:[12,13]}]

I want to find the maximum value of X and find the maximum value of YValues separately.

I don't expect for loop to find the maximum value. Expecting in simple way to find the maximum of X as well as maximum of YValues from points JSON object.

Is it possible to use Math.max or any custom function ?

Thanks, Siva

Something like this?

Math.max.apply(0,points.map(function(v){return v.x}));

Still a loop, but it's succinct.

Here's how to do it for YValues . A long line though:

Math.max.apply(0,[].concat.apply([],arr.map(function(v){return v.YValues})));

I made soultion using javascript 1.8 Array reduce method . Please note it works only in modern browsers

var max = yourObj.points.reduce( function ( a, b ){
    a.x = Math.max.apply( 0, [a.x,b.x] ) ;
    a.y = Math.max.apply( 0, [].concat( [ a.y ], b.YValues ) )
    return a;
}, { x :0, y :0 } );

the max variable contains maximum x and y

console.log( max.x );
console.log( max.y );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM