Home > database >  Recursive Way to Find & Assign Correct Value
Recursive Way to Find & Assign Correct Value

Time:11-20

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'.

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related