David Weng
David Weng

Reputation: 4235

jQuery getting specific properties of an array

I have an array of image elements, I want to find the biggest height value.

So, if I have

[
    <img src="image1.jpg" width="300" height="400" />, 
    <img src="image2.jpg" width="200" height="500" />,
    <img src="image3.jpg" width="100" height="200" />
]

The number that I want is 500.

What's the best way to achieve this?

Upvotes: 1

Views: 310

Answers (3)

semiadam
semiadam

Reputation: 91

Let's say your images are in an array called a:

a.sort(function(a,b) {return $(a).height() < $(b).height() } ) ; 
alert($(a[0]).height()) ;

Make sure you have single quotes around your image tags:

a = [
   '<img src="image1.jpg" width="300" height="400" />', 
    '<img src="image2.jpg" width="200" height="500" />',
    '<img src="image3.jpg" width="100" height="200" />'
] ;

Upvotes: 0

maerics
maerics

Reputation: 156414

You can also try this strategy, assuming your images are stored in the array "imgs":

var maxHeight = Math.max.apply({}, imgs.map(function(x){return x.height}));
maxHeight; // => 500

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074148

I assume that you really have an array of img element instances (what you've shown could be taken either way, elements or strings, but you haven't quoted them, so...).

You can also use jQuery's $.each:

var maxHeight = -1;
$.each(theArray, function() {
    if (maxHeight < this.height) {
        maxHeight = this.height;
    }
});

Or if you already have the array wrapped in a jQuery object:

var theArray = $('img'); // A jQuery object wrapped around an array of all `img`s

...then you can use each (which is slightly different from $.each):

var maxHeight = -1;
theArray.each(function() {
    if (maxHeight < this.height) {
        maxHeight = this.height;
    }
});

Or just use a boring old-fashioned loop:

var index, maxHeight;
maxHeight = -1;
for (index = 0; index < theArray.length; ++index) {
    if (maxHeight < theArray[index].height) {
        maxHeight < theArray[index].height;
    }
}

In all of the above, I've used the height property of the HTMLImageElement as specified by the DOM. Alternately, you may prefer jQuery's height() function (if so, don't forget to wrap the element in a jQuery object — e.g., $(this).height()), but normally height (the property) is all you need with img elements.

Upvotes: 4

Related Questions