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
   }
 ]
ray
  • 5,454
  • 1
  • 18
  • 40
Jakay
  • 40
  • 7

2 Answers2

1

You sort array as below,

Array.sort_by {|x|x['lead_stats']['total_leads']}.reverse
ray
  • 5,454
  • 1
  • 18
  • 40
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.

ray
  • 5,454
  • 1
  • 18
  • 40