I tweaked the code slightly with the following inclusions:
values(), instead of the collection as-isIn addition, the sorting function is not entirely redundant as earlier assumed, since the behavior varies, depending on incoming parameter
Putting it all together, we have:
protected function punctualChart ($attendanceCollection, ?string $puncMode) {
$puncMode = $puncMode?? "ear";
$attendanceDays = $attendanceCollection->groupBy(function ($attendance) {
return $attendance->created_at->format("m-d");
})
->map(function ($daysCollection) use ($puncMode) { // then sum their value for each day? add their indexes. depending on the mode, we know whether highest or lowest is the winner
return $puncMode == "ear"? $daysCollection->sortByDesc("created_at")->values():
$daysCollection->sortBy("created_at")->values();
});
//dd($attendanceDays, $puncMode);
$scoreEmployee = [];
$maxValue = 0;
foreach ($attendanceDays as $attendanceCollection) {
foreach ($attendanceCollection as $index => $attendance) {
$employeeId = /*$attendance->employee->last_name.*/$attendance->employee_id;
if (!array_key_exists($employeeId, $scoreEmployee))
$scoreEmployee[$employeeId] = /*0;*/[
"value" => 0,
"model" => $attendance->employee, //->last_name
];
$maxValue += $index+1;
$scoreEmployee[$employeeId]["value"] += $index+1; // offset 0-based index
}
}
foreach ($scoreEmployee as $employeeId => &$employeeDetails)
$employeeDetails["value"] = round(
($employeeDetails["value"]/$maxValue)*100,
2
);
//dd($scoreEmployee);
return $scoreEmployee;
}
Thanks to @angel for motivating me to give this another shot
reassign the indexes to the resulting collection