Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda