This works, and I personally find it elegant and kind of "neat," but then I worry it's a bit too tricky. Comments welcome:
function (reports) {
reports.forEach(function (report, i) {
report.upPercentage = report.upTime / report.totalTime;
report.rank = i; // temporary storage in a convenient location
});
_.sortBy(reports, 'upPercentage').forEach(function (report, i) {
reports[report.rank].rank = i; // the 'trick'
});
return reports;
}
The first loop goes through the array of reports, and calculates the upPercentage
for each report. This part should arguably be done on the backend but it isn't and it isn't going to be. Not my call.
The first loop also assigns each element's own position in the array to its rank
. This is not the report's actual rank, it's just data I need for the second loop.
The second loop is iterating over a sorted copy of the reports
array (it is important that the original sorting of reports
be maintained), and uses the element's original position, stored in rank
, to find it in the original, unsorted array. It then assigns the element's position in the sorted array to the rank
of the element in the original, unsorted array.
Thus rank
ends up being equal to the number of reports that have a lower upPercentage
than does the given report.
report.upPercentage = reports.upTime / reports.totalTime
result in every report having the same upPercentage? Is upTime supposed to be a property of the reports collection or of an individual report? \$\endgroup\$