最小和最大的多维数组 [英] Min and max in multidimensional array

查看:143
本文介绍了最小和最大的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组是:

var a = new Array();
a[0] = {x: 10,y: 10};
a[1] = {x: 20,y: 50};
a[2] = {x: 30,y: 20};
a[3] = {x: 10,y: 10};

VAR分钟= Math.min.apply(NULL,a.x)不起作用。
一些想法?

var min = Math.min.apply(null, a.x) doesn't work. Some ideas?

推荐答案

您曾与。适用,但你需要传递<$ C的集合正确的观念$ C> X 值。

You had the right idea with .apply but you need to pass a collection of the x values.

var xVals = a.map(function(obj) { return obj.x; });
var min = Math.min.apply(null, xVals);


.MAP()方法使得包括任何你在每个迭代中返回的新数组。


The .map() method makes a new Array comprised of whatever you returned in each iteration.

[10, 20, 30, 10]


然后传递数组作为第二个参数。适用将分布在阵列作为单独的参数的成员。因此,这好像你这样做:


Then passing the Array as the second argument to .apply will distribute the members of the Array as individual arguments. So it's as though you did this:

Math.min(10, 20, 30, 10) // 10


不过,因为你需要 .MAP(),你不妨跳过 Math.min ,和只需使用。降低代替。


But since you need to .map(), you might as well skip the Math.min, and just use .reduce instead.

var min = a.reduce(function(min, obj) { 
                      return obj.x < min ? obj.x : min; 
                   }, Infinity);

这篇关于最小和最大的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆