How-to sort employments in JavaScript
Introduction
If there is a need to sort all employments of a Core Identity within a workflow, you can use the script below.
Step 1 - Describe step 1
// return 1: sort a after b, e.g. [b, a]
// return -1: sort a before b, e.g. [a, b]
// return 0: keep original order of a and b
function employmentSorter(a, b) {
var boolA = a.employment_state.system_name == "Deleted";
var boolB = b.employment_state.system_name == "Deleted";
if (boolA && !boolB) {
return 1;
} else if (!boolA && boolB) {
return -1;
} else {
if (a.employment_state.id > b.employment_state.id) {
return -1;
} else if (a.employment_state.id < b.employment_state.id) {
return 1;
} else {
if (a.main_employment && !b.main_employment) {
return -1;
} else if (!a.main_employment && b.main_employment) {
return 1;
} else {
var today = new Date(Date.now());
boolA = new Date(a.valid_from) <= today && (!a.valid_to || new Date(a.valid_to) >= today);
boolB = new Date(b.valid_from) <= today && (!b.valid_to || new Date(b.valid_to) >= today);
if (boolA && !boolB) {
return -1;
} else if (!boolA && boolB) {
return 1;
} else {
if (a.percentage > b.percentage) {
return -1;
} else if (a.percentage < b.percentage) {
return 1;
} else {
if (a.valid_from < b.valid_from) {
return -1;
} else if (a.valid_from > b.valid_from) {
return 1;
} else {
if (a.valid_to && !b.valid_to) {
return 1;
} else if (!a.valid_to && b.valid_to) {
return -1;
} else {
if (new Date(a.valid_to) < new Date(b.valid_to)) {
return 1;
} else if (new Date(a.valid_to) > new Date(b.valid_to)) {
return -1;
} else {
if (a.id < b.id) {
return -1;
} else if (a.id > b.id) {
return 1;
} else {
return 0;
}
}
}
}
}
}
}
}
}
}
So given an employment Array as a result of a GetAllCoreIdentityEmploymentActivity
(with loaded properties valid_from
, valid_to
, percentage
, id
, main_employment
; and loaded attributes employment_state.id
, employment_state.system_name
), it can be sorted like this:
employments.sort(employmentSorter);
After this sort, the main employment is at employments[0]
© ITSENSE AG. Alle Rechte vorbehalten. ITSENSE und CoreOne sind eingetragene Marken der ITSENSE AG.