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

167
Views
Recursive Way to Find & Assign Correct Value

I have a situation where I need to find a value from an array of objects, depending on the object that has the highest value for a property named sequence. When I find the object with the highest numeric value for sequence then I want to assign the value of variable to the value of another property on that same object. I could do this with a long loop with numerous conditionals, but I'm wondering if there's a simpler way to do this via some kind of recursive process.

My data look like this:

let endDate;

let data = [
  {
    clientId: 912,
    coverage: {
      start: '2021-07-30',
      finish: '2021-12-31',
      agent: {
        name: 'Second',
        sequence: 2
      },
    }
  },
    {
    clientId: 912,
    coverage: {
      start: '2021-08-01',
      finish: '2021-12-20',
      agent: {
        name: 'First',
        sequence: 1
      },
    }
  },
    {
    clientId: 912,
    coverage: {
      start: '2021-09-13',
      finish: '2021-12-25',
      agent: {
        name: 'Third',
        sequence: 3
      },
    }
  },
];

What I want do do is set a variable named subscriptionEndDate to the value of finish on whatever object from the above array that has the highest numeric value for coverage.agent.sequence.

The result for endDate for the above data should be '2021-12-25'.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You don't need recursion as you'll only need to iterate over the array and get the client with max sequence, you can use Array#reduce as follows:

const data = [
  { clientId: 912, coverage: { id: 59307, start: '2021-07-30', finish: '2021-12-31', agent: { name: 'Third', sequence: 2 } } },
  { clientId: 912, coverage: { id: 59307, start: '2021-08-01', finish: '2021-12-20', agent: { name: 'First', sequence: 1 } } },
  { clientId: 912, coverage: { start: '2021-09-13', finish: '2021-12-25', agent: { name: 'Second', sequence: 3 } } }
];

const clientWithHighestSequence = data.reduce((maxSeqClient, client) => 
  client.coverage.agent.sequence > (maxSeqClient?.coverage.agent.sequence ?? 0)
    ? client
    : maxSeqClient
, null);

console.log(clientWithHighestSequence);

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!