Reputation: 53246
The title of this question might be a little misleading, but it was the closest to accurately describe the problem I was having.
I am currently working on a custom lightbox script, similar to the one that can be found on Facebook and airbnb. Once the user clicks on an image, the lightbox is not resized to the content, rather the image is centered with a black area around it (if you're a regular FB user, you should know what I mean).
I am storing the images to be used for the lightbox in an JS array as follows (generated from a MySQL database:
var item_images = [
{ 'id': 2, 'url': '50929ab7ae8e5.jpg', 'caption': 'My Photo # 1', 'width': 1000, 'height': 750 },
{ 'id': 7, 'url': '50929ab7ae8e8.jpg', 'caption': 'My Photo # 1', 'width': 1000, 'height': 800 },
{ 'id': 3, 'url': '50929ac161d10.jpg', 'caption': 'My Photo # 2', 'width': 1000, 'height': 750 },
{ 'id': 4, 'url': '50929acbe8dc8.jpg', 'caption': 'My Photo # 3', 'width': 1000, 'height': 750 }
];
I need a function in JS to find the largest width and largest height required for the images. For example, given the data above, I'd like a function GetMaxSizes()
which will return 800
(largest height in the array) and 1000
(the largest width in the array).
Is there a more efficient way than looping over the entire array and comparing everything? My concern is this will become slow if there are lots of elements inside item_images
:
function GetRequiredHeight()
{
var req_height = 0,
req_width = 0;
for(var i in item_images)
{
var image = item_images[i];
if(image.width > req_width) { req_width = image.width };
if(image.height > req_height) { req_height = image.height };
}
return { width: req_width, height: req_height };
}
Upvotes: 1
Views: 121
Reputation: 12685
This is O(n) complexity, and I can't imagine anything better than that. Iteration through array having 10000 elements is not a big deal for many many years. How many pics would you like to store here? Milions? If your algorithm slows down, I would search for different reasons.
I assume you do this iteration once. If you want to alter this array frequently, some optimizations could be done to avoid traversing whole array whole the time. I have some good idea but it's more writing, so if you need it please comment this answer.
Upvotes: 1