I'm trying to find a way to extract from an array of objects one specific object which has one value higher than another object.
The particularity is that I can have multiple objects and I need to find 2 or more which have the same key/value called role: GUARDIAN and then extract the one which has a higher value on the key `signOrder.
An array example
[
{
....
signOrder: 1,
role: 'CONSENTEE',
},
{
signOrder: 2,
role: 'GUARDIAN',
},
{
role: 'GUARDIAN',
signOrder: 3
}
]
Cases
I'm getting an array-like above but there is only one guardian so I'm extracting only that guardian information
I'm getting 2 guardians as above and need to extract the guardian with the highest number signOrder = 3
what will be the best way to do this in the right way to have the output of the 2 points above as
Output 1 I have only one guardian so I take that one
{
role: 'GUARDIAN',
signOrder: 2
}
Output 2 I have multiple Guardians so I take the one with the highest signOrder
{
role: 'GUARDIAN',
signOrder: 3
}
const roles = [
{
signOrder: 1,
role: 'CONSENTEE',
},
{
signOrder: 2,
role: 'GUARDIAN',
},
{
role: 'GUARDIAN',
signOrder: 3
}
];
const getHighestByRole = (roles, roleToFind) => {
// Get all objects for given role
const foundRoles = roles.filter(({ role }) => role === roleToFind);
// Sort them by `signOrder` then return first item
return foundRoles.sort((a, b) => b.signOrder - a.signOrder)[0];
}
console.log(getHighestByRole(roles, 'GUARDIAN'));
console.log(getHighestByRole(roles, 'CONSENTEE'));