最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Min and max in multidimensional array - Stack Overflow

programmeradmin5浏览0评论

My array is:

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 min = Math.min.apply(null, a.x) doesn't work. Some ideas?

My array is:

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 min = Math.min.apply(null, a.x) doesn't work. Some ideas?

Share Improve this question edited Feb 23, 2013 at 16:46 JJJ 33.2k20 gold badges94 silver badges103 bronze badges asked Feb 23, 2013 at 16:41 BendegúzBendegúz 7667 silver badges15 bronze badges 4
  • 1 a.x is not defined, what are you trying to do exactly? – Musa Commented Feb 23, 2013 at 16:44
  • possible duplicate of find max value of a child object – JJJ Commented Feb 23, 2013 at 16:45
  • this is a coords system, i want to max X min X max Y and min Y with a simple code – Bendegúz Commented Feb 23, 2013 at 16:47
  • Yes, and the duplicate shows how. – JJJ Commented Feb 23, 2013 at 16:50
Add a ment  | 

1 Answer 1

Reset to default 9

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

The .map() method makes a new Array prised 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

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);
发布评论

评论列表(0)

  1. 暂无评论