Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Sort objects by sum of array

Each of my users has an array of integers. The users attend a competition and I would like to sort them by the sum of the first 7 elements of their array. I know how to do each part individually, but I'm not sure how to put it together and display it in the show.

inside the def show

@competition.users.sort_by{|e| e.daily.first(7).sum}
for comp in @competition.users
  p comp.name
  p comp.daily #Their array
end

This is how I get the sum of the first 7 elements (currently used in my view):

user.daily.first(7).sum

thanks

like image 340
Marcus Avatar asked Aug 23 '26 15:08

Marcus


1 Answers

This would sort the users in the descending order of their sum. User with highest sum will be in the top. Remove the - for ascending sort

@sorted_users = @competition.users.sort_by{|user| -user.daily.first(7).sum}
for comp in @sorted_users
  p comp.name
  p comp.daily #Their array
end

Or you can use sort_by! which will do inplace sorting

@competition.users.sort_by!{|user| -user.daily.first(7).sum}
for comp in @competition.users
  p comp.name
  p comp.daily #Their array
end
like image 102
usha Avatar answered Aug 27 '26 01:08

usha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!