StandardNerd StandardNerd - 4 months ago 29
Ruby Question

Ruby: Sort array of objects after an array of name properties

I have an array "sizes" that look like this:

[#<OPTIONVALUE ID: 5, NAME: "M">,
#<OPTIONVALUE ID: 6, NAME: "M/L">,
#<OPTIONVALUE ID: 7, NAME: "XS/S">]


Consider the values of attribute NAME. The array is sorted: M, M/L, XS/S.

But the sort order should look like this:

@sizes_sort_order = ["XS", "XS/S", "S", "S/M", "M", "M/L", "L", "L/XL", "XL"]


applied to the former array the order of the elements should look like this:

[#<SPREE::OPTIONVALUE ID: 7, NAME: "XS/S">,
#<SPREE::OPTIONVALUE ID: 5, NAME: "M">,
#<SPREE::OPTIONVALUE ID: 6, NAME: "M/L">]

def sizes
@sizes ||= grouped_option_values_by_option_type[Spree::OptionType.find_by!(name: 'size')]
@sizes_sort_order = ["XS", "XS/S", "S", "S/M", "M", "M/L", "L", "L/XL", "XL"]
@sizes.map { # sort after @size_sort_order }
end


How can i achieve to get the elements in the array sorted after @sizes_sort_order ?

Answer

You can use Enumerable#sort_by

my_array.sort_by {|x| @sizes_sort_order.index(x.name) }