1

I am new to rails. how to sort total leads in my array of hash. total leads maximum values should be first.

Array  = [
  {
    "project_name"=>"Godrej United",
    "lead_stats"=>{ 
       "total_leads"=>1, 
       "untouched_leads"=>0, 
       "dumped_leads"=>1, 
       "not_responding"=>0, 
       "switched_off"=>0, 
       "hot_leads"=>1, 
       "cold_leads"=>1, 
       "warm_leads"=>0
     },
     "project_id"=>2
   },
   {
     "project_name"=>"Golden Panorama", 
     "lead_stats"=>{
       "total_leads"=>5, 
       "untouched_leads"=>0, 
       "dumped_leads"=>1, 
       "not_responding"=>0, 
       "switched_off"=>0, 
       "hot_leads"=>0, 
       "cold_leads"=>0, 
       "warm_leads"=>0
     }, 
     "project_id"=>10
   }
 ]
2
  • Please check my updated answer Commented Mar 1, 2019 at 6:17
  • @Vishal Yes I had your benchmark already from stackoverflow.com/a/2651028/10522579 Commented Mar 1, 2019 at 6:19

2 Answers 2

1

You sort array as below,

Array.sort_by {|x|x['lead_stats']['total_leads']}.reverse
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it as below,

Array.sort_by {|x| -x['lead_stats']['total_leads'] }

Alternative for answer is below,

Array.sort { |a,b| b['lead_stats']['total_leads'] <=> a['lead_stats']['total_leads'] }

Replace a and b in block to get in reverse order.

1 Comment

...or Array.max_by(Array.size) { ... }.

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.