Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda