繁体   English   中英

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

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

请找到以下数组JSON对象。

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

我想分别找到X的最大值和YValues的最大值。

我不希望for循环找到最大值。 以简单的方式期望从points JSON对象中找到X最大值以及YValues最大值。

是否可以使用Math.max或任何自定义函数?

谢谢西瓦

像这样吗

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

仍然是一个循环,但简洁。

这是针对YValues 一长行:

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

我使用JavaScript 1.8 Array reduce方法制作了soultion。 请注意,它仅在现代浏览器中有效

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 } );

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