1

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

The code isn't quite right, but the idea behind it is exactly what I was looking for. Thanks.
0

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" />'
] ;

1 Comment

This works fine but if the array is really long then performance of this solution will poor, since it is O(n*lg(n)), whereas others are O(n). But in reality, probably doesn't matter for a "small" number of images.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.