Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

javascript - Min and max in multidimensional array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...