• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

117
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 3 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 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda