Discover pictures that perfectly match the optimal container dimensions

Looking to develop a function that can determine the best fitting image based on its size relative to its container.

  • The image should not exceed the dimensions of the container either in width or height.
  • The selected image should have minimal empty space around it min(space).

I experimented with a simple JavaScript solution but I'm unsure if it's both efficient and elegant.

let arr = [{'id': 1, 'width': 10, 'height': 10},
{'id': 2, 'width': 20, 'height': 20},
{'id': 3, 'width': 30, 'height': 30},
{'id': 4, 'width': 40, 'height': 40},
{'id': 5, 'width': 50, 'height': 50}]

let height = 25
let width = 25

let best_min_height_delta = Infinity
let best_min_width_delta = Infinity
let best_empty_space = Infinity
let selected_id = -1

arr.forEach(element => {

  if (height >= element.height && width >= element.width) {

      let delta_height = height - element.height
      let delta_width = width - element.width 

      if (delta_height < best_min_height_delta && delta_width < best_min_width_delta) {
      
        let empty_space = delta_width + delta_width
        
        if (empty_space < best_empty_space) {
                    best_min_width_delta = delta_width
                  best_min_height_delta = delta_height
                  best_empty_space = empty_space
                  selected_id = element.id
        }
        
      }
  }
  
})

console.log('the winner is: ' + selected_id) 

Answer №1

When dealing with a rectangular box, the empty space can be calculated by subtracting the area of the inner box from the area of the bounding box. For example:

let total_empty_space = (boxWidth * boxHeight) - (innerBox.width * innerBox.height);

It's important to point out that currently you are defining total_empty_space as delta_width + delta_width, which doesn't appear to be correct.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Separate the divs in a template into individual templates, or alternatively, utilize ng-if to display different divs within a single template

As a newcomer to AngularJS, I am seeking advice on the most efficient way to code for the given scenario: Scenario: I have a single HTML template containing multiple divs, and I need to display only one div at a time based on specific conditions. Two app ...

Mistake in maintaining hydration with styled-components and React Context

I encountered an issue where I have two theme variants in my app - dark and light. You can view the sandbox example here ThemeContext.ts export const ThemeContext = createContext<{ theme: AppThemeInterface, setTheme: Dispatch<SetStateAction< ...

Swapping out the document.createElement() method for React.createElement()

In a JavaScript library, I utilize document.createElement() to create an HTMLElement. Now, I am looking to develop a React library with the same functionality. My initial thought was to substitute document.createElement() with React.createElement(). There ...

Combining strings in a loop using Javascript

I have a loop hash data stored in a variable called rec. var rec = { }; for (var b = 0; b < 2; b++) { rec['id'+b] = b</p> } Next, I have a piece of JavaScript code that creates a template for a table. var template ='<tab ...

What causes the slowness of onsubmit=" " function?

Initially, I had the following setup: HTML: <form onsubmit="return validate()"> ... <input type="submit" id="submit-button"/> </form> JS: function validate() { // Extensive validation process with regex and more... $(& ...

Out of nowhere, jQuery suddenly fails to recognize that my checkbox has been selected

http://pastebin.com/r30Wfvi3 Out of the blue, all that functionality suddenly ceased. var showMyLocation = document.createElement('input'); showMyLocation.type = "checkbox"; showMyLocation.className = "checkboxForRange"; showMyLocation.id = "sh ...

Is there a method to have JavaScript display all the information during a SQL while loop?

I'm currently working on implementing a timer for my script. However, I am facing an issue where the timer only counts down from the last result instead of each individual result returned from the query. Any assistance with resolving this problem woul ...

The jQuery function for $(window).scroll is not functioning as expected

My challenge is getting the scroll to reveal my scrollTop value I've been working with this code: $(document).ready(function(){ console.log('Hello!'); $(window).scroll(function(){ console.log('Scrolling...'); var wScroll = ...

Unable to display PHP response in a div using AJAX - issue persisting

Hey there! I'm currently working on a project where I want the form submission to load a response into a div without refreshing the page. I've looked at various examples of ajax forms with PHP online, but haven't been able to solve my issue ...

Designing a query feature to explore a Sequel Database utilizing a 'RETRIEVE' approach

In my index.erb, I've created a search bar with the following code: <nav> <div class="nav-wrapper"> <form> <div class="input-field"> <input id="search" type="search" placeholder="Search..." required> ...

Save the input from an HTML text area tag as a Word or PDF file using C# code

In the midst of a challenging ASP .NET project, there is a need to download the content of a text area as a file in formats like .doc, .pdf, and .txt. While it's common knowledge that plain text can be downloaded as .txt using JavaScript, the real qu ...

Error: The Vuex store is not defined in the Vue.js component when attempting to access it using

I've recently set up a new vue-cli webpack project with Vuex. I have initialized my Vuex store in store.js like so: import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); const store = new Vuex.Store({ state: {} }); export default store; ...

What is the best way to store changing images in a Next.js application?

Is it possible to set the cache-control for images in a list of objects received from an API? Each object in the list contains a property called imageUrl, which is the link to the image. ...

Random sequencing of the commands

Whenever I call the Details function, it returns empty details because the function executes before retrieving data from the json file. What is the best way to fix this issue? app.controller('loginCtrl',function($scope,login){ $scope.user=login ...

How to handle Object data returned asynchronously via Promises in Angular?

Upon receiving an array of Question objects, it appears as a data structure containing question categories and questions within each category. The process involves initializing the object with board: JeopardyBoard = new JeopardyBoard();. Subsequently, popu ...

Is there a way to eliminate text from a barcode image using JavaScript or TypeScript?

This is my unique html code <div class="pr-2" style="width: 130px"> <div *ngIf="!element.editing" > <span class="ss">{{element.barcode}}</span> </di ...

What is the ideal usage of promises in ES6 node projects?

The official bluebird promises page suggests that when using node.js, there may not be a need to manually write promises. Recently, while working on a new project, I noticed that my code heavily relies on promises. For instance, I have a databaseConnector ...

The Facebook debugging tool is unable to detect meta tags for SEO in Next.js

This question feels all too familiar, as if it has been asked numerous times before. It must be a challenging one. Let me add some more detail from my end to see if it sheds light on the issue. Currently, I am working with Next.js ^10.0.9 and next-seo ^4. ...

What steps should I take to address the issue of the document not being defined?

I encountered an error that I initially thought was related to node.js, but now I'm not entirely sure. How can I go about resolving this issue? [Running] node "c:\Users\Lenovo\Desktop\projectjs\index.js" c:\User ...

Can a table with a checkered pattern be created in Ember.js with just Handlebars and ember-composable-helpers?

I'm new to working with Ember.js and I am attempting to create a simple checkered table. In my project, I am utilizing Bootstrap 4, ember-composable-helpers, and Handlebars. Is there anyone who can guide me on achieving this goal WITHOUT the use of ja ...