Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing & sorting array of hashes in Ruby

Tags:

ruby

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}]
like image 956
user2980169 Avatar asked Sep 09 '15 16:09

user2980169


People also ask

What do you mean comparing?

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.

What is comparing and examples?

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.

Is comparing to correct?

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.


2 Answers

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}]
like image 65
Stefan Avatar answered Nov 14 '22 22:11

Stefan


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).

like image 31
Zach Langley Avatar answered Nov 14 '22 22:11

Zach Langley