Dustin Halstead
Dustin Halstead

Reputation: 771

JavaScript: De-duplicate and Count Properties of Array

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 ...


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.

Upvotes: 0

Views: 66

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138497

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)
   };
 });

Upvotes: 1

Related Questions