I'm having a bit of trouble with selecting arrays in an objects with greatest value.
Here is an object I end up having through series of functions.
{
1252 = {
[Monday, {
Teacher1 = {
Periods = [
[06/02/2023, 30/06/2023, 146 days]
]
},
Teacher2 = {
Periods = [
[21/11/2022, 05/02/2023, 74 days]
]
}
}]
}
}
Basically it means : Ok I have two different teachers on Monday, with each a different period of occupation and the number of days for each.
What I'm looking to return is :
- for the reference 1252, the main teacher is Teacher1 (because he has 146 days of occupation), that info should be independant in an array like [[ref, day, mainTeacher, startDate, endDate, numberOfDays]]
- To be able to retrieve the info that there is a second Teacher with less days.
Thank you if you can help me get on the right track !
Best
Cédric
CodePudding user response:
First what you posted is not a JSON object, it does not follow JSON object notation. I think this is what you are looking for:
const inputData = {
"1252": [
"Monday",
{
"Teacher1": {
"Periods": [ [ "06/02/2023", "30/06/2023", "146 days" ] ]
},
"Teacher2": {
"Periods": [ [ "21/11/2022", "05/02/2023", "74 days" ] ]
}
}
]
};
const result = [
[ "1252", "Monday", "Teacher1", "06/02/2023", "30/06/2023", "146 days" ],
[ "1252", "Monday", "Teacher2", "21/11/2022", "05/02/2023", "74 days" ],
]
// Defined data cleanup method
function cleanData(data = null) {
if (!data) return null;
const result = [];
// Loop through the data
for (const ref in data) {
const [day, teachers] = data[ref];
// loop through the teachers
for (const teacher in teachers) {
const [[startDate, endDate, numberOfDays]] = teachers[teacher].Periods;
// Gather all the data into result
result.push([ref, day, teacher, startDate, endDate, numberOfDays]);
}
}
return result;
}
function getMostDays( records=null ){
if (!records) return null;
let days;
let result;
// Loop through records
for ( const record of records ){
const [ ref, day, teacher, startDate, endDate, numberOfDays ] = record;
// Convert string to int
const len = parseInt( numberOfDays );
// Compare previous record days with current record days
if ( days && len < days ) continue;
days = len;
result = record;
}
return result;
}
function getLeastDays( records=null ){
if (!records) return null;
let days;
let result;
// Loop through records
for ( const record of records ){
const [ ref, day, teacher, startDate, endDate, numberOfDays ] = record;
// Convert string to int
const len = parseInt( numberOfDays );
// Compare previous record days with current record days
if ( days && len > days ) continue;
days = len;
result = record;
}
return result;
}
// Run data cleanup to get array of arrays
cleanData( inputData );
// Run to return the teacher with most days
getMostDays( cleanData( inputData ) );
// Run to return the teacher with least days
getLeastDays( cleanData( inputData ) );