-1

I have tried reading on SO and elsewhere but could only find single level objects and couldn't make this work for multilevel objects. ie: return tableData sorted on value descending.

I have the below object which I am attaching in debug and console view:

enter image description here enter image description here

And this is the actual object:

"[{"name":"Sepitomo",
"years":[  
   {  
      "year":"Italy",
      "value":25.79
   },
   {  
      "year":"Spain",
      "value":30.68
   },
   {  
      "year":"France",
      "value":18.31
   },
   {  
      "year":"Poland",
      "value":9.45
   },
   {  
      "year":"Portugal",
      "value":6.72
   },
   {  
      "year":"Switzerland",
      "value":4.05
   },
   {  
      "year":"Romania",
      "value":3.95
   },
   {  
      "year":"[Cash]",
      "value":3.2
   },
   {  
      "year":"Belgium",
      "value":3.18
   },
   {  
      "year":"United Kingdom",
      "value":2.94
   },
   {  
      "year":"Ireland",
      "value":2.01
   },
   {  
      "year":"Germany",
      "value":0.98
   }
]
},
{  
"name":"Benchmark",
"years":[  
   {  
      "year":"Italy"
   },
   {  
      "year":"Spain"
   },
   {  
      "year":"France"
   },
   {  
      "year":"Poland"
   },
   {  
      "year":"Portugal"
   },
   {  
      "year":"Switzerland"
   },
   {  
      "year":"Romania"
   },
   {  
      "year":"[Cash]"
   },
   {  
      "year":"Belgium"
   },
   {  
      "year":"United Kingdom"
   },
   {  
      "year":"Ireland"
   },
   {  
      "year":"Germany"
   }
]
}
]"

I need to return the tableData object sorted on the value and also return the other objects as they are in the same structure (also return the other sections not sorted).

I tried sorting-object-properties-based-on-value, sorting-javascript-object-by-property-value3 amongst others

Afshin Ghazi
  • 2,784
  • 4
  • 23
  • 37

1 Answers1

0

Solved by first setting up compare then sorting as below then assigning to original object

 let temp2 = tableData[0].years;

 function compareValues(a, b) {
   if (a.value > b.value)
          return -1;
   if (a.value < b.value)
          return 1;
   return 0;
 }


tableData[0].years = temp2.sort(compareValues);
Afshin Ghazi
  • 2,784
  • 4
  • 23
  • 37