yandex
loader

please wait

  • Shiv Thapa Mar-13-2019 01:05:13 PM ( 2 months ago )

    I have an array of arrays:

    x = [
      ["ready", 5], ["shipped", 1], ["pending", 1], ["refunded", 1],
      ["delivered", 23], ["scheduled", 1], ["canceled", 51]
    ]

    My sorting array is

    order_array = [
      "ready", "in_progress", "recieved", "shipped", "scheduled", "pick_up",
     "delivered", "canceled", "failed", "refunded", "refund_failed"
    ]

    I need to order x based on the value of the first element in each subarray. The required sorted array is:

    [
      ["ready", 5], ["shipped", 1], ["scheduled", 1], ["delivered", 23],
      ["canceled", 51], ["refunded", 1]
    ]

    Using sort_by doesn't result in the required sorting, it leads to the same array.

    result = x.sort_by {|u| order_array.index(u)}
    # => [
    #      ["ready", 5], ["shipped", 1], ["pending", 1], ["refunded", 1],
    #      ["delivered", 23], ["scheduled", 1], ["canceled", 51]
    # ]

     

  • Apoorva Saxena Mar-13-2019 01:07:20 PM ( 2 months ago )
    h = x.to_h
    # => {"ready"=>5,
    # "shipped"=>1,
    # "pending"=>1,
    # "refunded"=>1,
    # "delivered"=>23,
    # "scheduled"=>1,
    # "canceled"=>51}
    
    order_array.map{|key| [key, h[key]] if h.key?(key)}.compact
    # => [["ready", 5],
    # ["shipped", 1],
    # ["scheduled", 1],
    # ["delivered", 23],
    # ["canceled", 51],
    # ["refunded", 1]]

    or

    h = x.to_h{|k, v| [k, [k, v]]}
    #=> {"ready"=>["ready", 5],
    # "shipped"=>["shipped", 1],
    # "pending"=>["pending", 1],
    # "refunded"=>["refunded", 1],
    # "delivered"=>["delivered", 23],
    # "scheduled"=>["scheduled", 1],
    # "canceled"=>["canceled", 51]}
    
    order_array.map{|k| h[k]}.compact
    #=> [["ready", 5],
    # ["shipped", 1],
    # ["scheduled", 1],
    # ["delivered", 23],
    # ["canceled", 51],
    # ["refunded", 1]]

    or

     

    h = x.to_h{|k, v| [k, [k, v]]}
    #=> {"ready"=>["ready", 5],
    # "shipped"=>["shipped", 1],
    # "pending"=>["pending", 1],
    # "refunded"=>["refunded", 1],
    # "delivered"=>["delivered", 23],
    # "scheduled"=>["scheduled", 1],
    # "canceled"=>["canceled", 51]}
    
    h.values_at(*order_array).compact
    #=> [["ready", 5],
    # ["shipped", 1],
    # ["scheduled", 1],
    # ["delivered", 23],
    # ["canceled", 51],
    # ["refunded", 1]]

Please login

Similar Discussion

Recommended For You