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

156
Vistas
How do you find the closest number in an array while using 2 identifiers?

Say I have an array of objects:

const arr = [
{num:3,numTwo:1},
{num:5,numTwo:3},
{num:7,numTwo:9},
{num:7,numTwo:3},
{num:8,numTwo:4}
]

const goal = 7

I have this code that properly finds the closest number when ONLY accounting for num:

const closest = arr.reduce(function (prev, curr) {
    return Math.abs(curr.num - goal) <
      Math.abs(prev.num - goal)
      ? curr
      : prev;
  });

It returns {num:7,numTwo:9} (because first instance), but I want numTwo to come into play where it returns the object with the lowest numTwo if in the case goal matches with multiple matching num's, so in this case it should return {num:7,numTwo:3}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Make your expression a subtraction and use || to involve the comparison of numTwo when that subtraction is 0:

const arr = [{num:3,numTwo:1},{num:5,numTwo:3},{num:7,numTwo:9},{num:7,numTwo:3},{num:8,numTwo:4}];
const goal = 7;

const closest = arr.reduce(function (prev, curr) {
    return (Math.abs(curr.num - goal) - Math.abs(prev.num - goal) 
            || curr.numTwo - prev.numTwo) < 0
        ? curr
        : prev;
});
  
console.log(closest);

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