Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
JavaScript Algorithm - Get the object with most similar area in array

I have the following object

const originalObject = {
   width: 1090,
   height: 723,
}

And this list of objects

const validObjects = [
   { 
       width: 1080,
       height: 1080
   }, 
   {
       width: 1080,
       height: 1350 
   },
   {
       width: 1080,
       height: 750
   }
]

Giving the following helper

const area = (width, height) => width * height;

I need to find the object from validObjects whose area most closely resembles that of the original object.

So if I do:

getMostSimilarObject(originalObject, validObjects)

I get:

{
   width: 1080,
   height: 750
}

as area(1080, 750) is the most close one to area(1090, 723)

Any ideas?

Note: In validObjects, there will only be around 3 to 10 objects.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can determine how "similar" two objects are (we'll call it "score") by summing the positive difference of the two object's width and height properties.

With this in mind, we can find the object most similar by getting the object with the lowest score in relation to originalObject. Simply loop through the list, calculate the score of the object and the item being looped through, and if the score is lower than the lowest recorded so far, replace the object.

The object at the end of the loop is the most "similar" object.

const validObjects = [{
    width: 1080,
    height: 1080
  },
  {
    width: 1080,
    height: 1350
  },
  {
    width: 1080,
    height: 750
  }
]

const originalObject = {
  width: 1090,
  height: 723,
}

function getMostSimilarObject(obj, list) {
  let score;
  let closest;
  list.forEach(e => {
    let objscore = Math.abs(obj.width - e.width) + Math.abs(obj.height - e.height)
    if (!score || objscore < score) {
      score = objscore;
      closest = e;
    }
  })
  return closest;
}

console.log(getMostSimilarObject(originalObject, validObjects))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!