Sort an array according to the elements of another array

后端 未结 4 1332
北荒
北荒 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:42
    hash_object = objects.each_with_object({}) do |obj, hash| 
      hash[obj.object_id] = obj
    end
    
    [1, 2, 3, 4, 5].map { |index| hash_object[index] }
    #=> array of objects in id's order
    

    I believe that the run time will be O(n)

    0 讨论(0)
  • 2020-11-28 09:43

    I like the accepted answer, but in ActiveSupport there is index_by which makes creating the initial hash even easier. See Cleanest way to create a Hash from an Array

    In fact you could do this in one line since Enumerable supports index_by as well:

    a2.index_by(&:id).values_at(*a1)
    
    0 讨论(0)
  • 2020-11-28 09:44

    I'll be surprised if anything is much faster than the obvious way:

    a2.sort_by{|x| a1.index x.id}
    
    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题