0

Working with arrays is definitely one of my weakest area, so any help is greatly appreciated.

To add to the challange, this is for a WebOS application that has the following limitations ...

  • JavaScript 5.0
  • Only extra library is JQuery
  • No arrow functions (=>)

Example of received array ...

var Schedule = [{
  "category": "Laboratory", "status": "COMPLETE" }, {
  "category": "Radiology" , "status": "COMPLETE" }, {
  "category": "Laboratory", "status": "SCHEDULED"}, {
  "category": "Laboratory", "status": "COMPLETE" }, {
  "category": "Radiology" , "status": "SCHEDULED"}, {
  "category": "Laboratory", "status": "COMPLETE" }, {
  "category": "Doppler"   , "status": "SCHEDULED"
}]

Desired conversion ...

var ScheduleFormatted = [{
  "category": "Laboratory", "complete": "3", "total": "4" }, {
  "category": "Radiology" , "complete": "1", "total": "2" }, {
  "category": "Doppler"   , "complete": "1", "total": "1" }, {
}]

It would be especially great to have the incomplete categories listed first.

I've been successful in achieving parts of this (like getting unique properties, or instance count by status), but the complexity of this has me completely stumped.

Please help.

Dustin Halstead
  • 741
  • 6
  • 19

1 Answers1

1

You could create lookup objects where you store the total / completed count for each category:

 var total = {}, complete = {};

 Schedule.forEach(function(item) {
    var c = item.category;
    total[c] = (total[c] || 0) + 1;
    if(item.status === "COMPLETED") 
      complete[c] = (complete[c] || 0) + 1;
 });

 var ScheduleFormatted = Object.keys(total).map(function(category) {
    return { 
     category: category, 
     total: "" + total[category],
     complete: "" + (complete[category] || 0)
   };
 });
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • That is an absolutely perfect solution! Thank you good sir. :) The only change I made was to add the following check before the return ... if (complete[category] == undefined) { complete[category] = 0; } ... Appreciate the help so very much. – Dustin Halstead Apr 20 '20 at 10:50
  • 1
    I see that you updated the answer to address the "complete" amount returning as "undefined" -- and in a much more elegant way than the "if" statement I included. Thank you again. – Dustin Halstead May 27 '20 at 08:29