Sort an array according to the elements of another array

后端 未结 4 1351
北荒
北荒 2020-11-28 09:07

I have an array of ids

a1 = [1, 2, 3, 4, 5]  

and I have another array of objects with ids in random order

a2 = [(obj_w         


        
4条回答
  •  青春惊慌失措
    2020-11-28 09:54

    Inspired by Eric Woodruff's Answer, I came up with the following vanilla Ruby solution:

    a2.group_by(&:object_id).values_at(*a1).flatten(1)
    

    Method documentation:

    • Enumerable#group_by
    • Array#values_at
    • Array#flatten

提交回复
热议问题