简体   繁体   English

如何在还包含一些JSON数组的JSON数组中查找最大值

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

Please find the below array JSON Object. 请找到以下数组JSON对象。

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. 我想分别找到X的最大值和YValues的最大值。

I don't expect for loop to find the maximum value. 我不希望for循环找到最大值。 Expecting in simple way to find the maximum of X as well as maximum of YValues from points JSON object. 以简单的方式期望从points JSON对象中找到X最大值以及YValues最大值。

Is it possible to use Math.max or any custom function ? 是否可以使用Math.max或任何自定义函数?

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 . 这是针对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 . 我使用JavaScript 1.8 Array reduce方法制作了soultion。 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 max变量包含x和y的最大值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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