I have two arrays. They have different attributes.
array1 = [{name: "apple", quantity: 2}, {name: "grape", quantity: 10}, {name: "pear", quantity: 3}]
array2 = [{name: "grape", freshness: 9}, {name: "apple", freshness: 7}, {name: "pear", freshness: 10}]
I would like to sort array1
based on array2
's order, by name. The result would be:
array1 = [{name: "grape", quantity: 10}, {name: "apple", quantity: 2}, {name: "pear", quantity: 3}]
1 : to point out as similar : liken She compared the activity of ants to the behavior of humans. 2 : to examine for similarity or differences Before buying compare the two bicycles. 3 : to appear in relation to others She compares well with the rest of the class.
Compare their voting records. The definition of compare means to find the similarities or differences between two or more people or things. An example of compare is noticing how much two sisters look alike. To be regarded as similar or equal.
Both are correct, but there is a small difference in meaning. "Compare to" expresses similarity between two things. For example: I hesitate to compare my own works to those of someone like Dickens.
You could build a name => index
hash:
h = array2.map { |e| e[:name] }.each_with_index.to_h
#=> {"grape"=>0, "apple"=>1, "pear"=>2}
And sort by that hash:
array1.sort_by { |e| h[e[:name]] }
#=> [{:name=>"grape", :quantity=>10}, {:name=>"apple", :quantity=>2}, {:name=>"pear", :quantity=>3}]
Here's a simple way to do it given your current data structure.
array1 = array1.sort_by { |x| array2.find_index { |y| y[:name] == x[:name] } }
However, note that find_index
takes O(n) time. This can be improved by using a different model for your data or by doing some preprocessing (e.g., see Stefan's answer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With