-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

2
  • 1
    Add code and not images of code Commented Jun 7, 2018 at 11:14
  • yeah add some code snippet and create fiddle Commented Jun 7, 2018 at 12:21

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.