4

Say I have an array like the following:

var myArray = new Array();
myArray[0] = {ValueA: 10, ValueB:900};
myArray[1] = {ValueA: 50, ValueB:190};

How would I select the element that has the smallest value for ValueA?

I've used the following to get the max of arrays of numbers before:

var largest = Math.max.apply(Math, myArray);

but i'm not sure how this method could be used to find the max/min of an array of objects. Suggestions?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • 1
    http://stackoverflow.com/questions/4020796/finding-max-value-in-multidimensional-json-array – mikey Oct 14 '11 at 00:13

2 Answers2

4

You could sort the array using a custom function then get the first and last members, e.g.

myArray.sort(function(a, b) {return a.ValueA - b.ValueA;});

Smallest:

myArray[0].ValueA;

Biggest:

myArray[myArray.length - 1].ValueA;

If you don't want to modify the order of your array, copy it first (the objects wont be copied, they'll just be referenced).

var myArray = new Array();
myArray[0] = {ValueA: 10, ValueB:900};
myArray[1] = {ValueA: 50, ValueB:190};
myArray[2] = {ValueA: 25, ValueB:160};
myArray[3] = {ValueA: 5, ValueB:10};

var copy = myArray.slice();
alert(copy.length);

copy.sort(function(a, b) {return a.ValueA - b.ValueA;});

alert(copy[0].ValueA); // 5
alert(copy[copy.length - 1].ValueA); // 50
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Nice -- what I would do. While this problem is solvable in `O(n)` bounds, `O(n lg n)` is generally quite sufficient (computer time is far cheaper than my development time :-) –  Oct 14 '11 at 00:54
0
Math.min.apply(Math,myArray.map(function(x){return x.ValueA;}));
tobyodavies
  • 27,347
  • 5
  • 42
  • 57
  • This does not work right away, but is an interesting solution. It would be great if you could expand on this a little more and maybe test it or provide a JSFiddle – netpoetica Sep 02 '13 at 16:30
  • The OP is not looking for the minimum *value*, but rather the object(s) which *have* that minimum value. – LondonRob Aug 10 '15 at 14:21