Home > Net >  JavaScript Algorithm - Get the object with most similar area in array
JavaScript Algorithm - Get the object with most similar area in array

Time:10-13

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 valid objects there will only be around 3 to 10 objects.

CodePudding user response:

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))

  • Related