Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!