I'm trying to solve a problem I have in my JS which is related to the following snippet
const signatureOrder = role => {
let order;
switch (role) {
case 'GUARDIAN':
order = 2;
break;
case 'ASSENTEE':
order = 3;
break;
case 'COUNTERSIGNEE':
order = 4;
break;
default:
order = 1;
break;
}
return order;
};
This method basically takes a role which currently is 4: CONSENTEE, GUARDIAN, ASSENTEE, COUNTERSIGNEE.
The CONSENTEE is always 1 and the order is always as the numbers from 1 to 5.
However, there can be a situation where I can have like multi roles coming:
1 consented
2 guardians
2 assentee
1 countersignee
This will be translated by the method in the following order
1 consented
2 Guardian
2 Guardian
3 Assentee
3 Assentee
4 Countersignee
This is not very correct and the output should be an increment of the single values but keeping the order fixed as below:
1 Consented
2 Guardian
3 Guardian
4 Assentee
5 Assentee
6 Countersignee
so what happens is that if we have already a guardian the next guardian becomes the previous guardian + 1 but stays always after Consentee and before Assentee.
The scenarios areas:
I would like to understand how to solve this in the right manner.
You can sort all your elements based on an orderArray. Then, assign the order based on the element index.
Based on this answer:
const orderArray = ['CONSENTEE', 'GUARDIAN', 'ASSENTEE', 'COUNTERSIGNEE']
const elements = ['CONSENTEE', 'ASSENTEE', 'GUARDIAN', 'COUNTERSIGNEE', 'ASSENTEE', 'GUARDIAN']
elements.sort(function(a, b){
return orderArray.indexOf(a) - orderArray.indexOf(b);
});
const withOrder = elements.map((el, i) => {
return {role: el, order: i+1}
})
console.log(withOrder)
It seems to me you need something like this:
const sortRoles = rolesArray => {
const orderOfRole = {
'CONSENTED': 1,
'GUARDIAN': 2,
'ASSENTEE': 3,
'COUNTERSIGNEE': 4
}
rolesArray.sort((role1, role2) => orderOfRole[role1] - orderOfRole[role2])
}
where, in the end, the order is just the index in the sorted array, incremented by 1:
roles = ['GUARDIAN', 'ASSENTEE', 'ASSENTEE', 'CONSENTED']
sortRoles(roles)
roles.map((role, index) => console.log(`${index + 1}: ${role}`))
// 1: CONSENTED
// 2: GUARDIAN
// 3: ASSENTEE
// 4: ASSENTEE
You can extend this to having an object for the role, instead of a string. In that case you just need to extract the string from the object in the comparison function of sort() and use it like above.