Find the highest value for a hash array with shared keys?

I have two arrays, each of which contains any number of hashes with the same keys, but with different values:

ArrayA = [{value: "abcd", value_length: 4, type: 0},{value: "abcdefgh", value_length: 8, type: 1}] ArrayB = [{value: "ab", value_length: 2, type: 0},{value: "abc", value_length: 3, type: 1}] 

Despite any number, the number of hashes will always be equal.

How can I find the largest :value_length for each hash whose value is of a particular type?

For example, the largest :value_length for a hash with a :type of 0 will be 4. The largest :value_length for a hash with a :type of 1 will be 8.

I just can't solve this problem.

+6
source share
4 answers

A simple way:

 all = ArrayA + ArrayB # Add them together if you want to search both arrays. all.select{|x| x[:type] == 0} .max_by{|x| x[:value_length]} 

And if you want to reuse it, just create a function:

 def find_max_of_my_array(arr,type) arr.select{|x| x[:type] == type} .max_by{|x| x[:value_length]} end p find_max_of_my_array(ArrayA, 0) # => {:value=>"abcd", :value_length=>4, :type=>0} 
+12
source

I'm not quite sure I know what result you want, but try this. I assume that the arrays are ordered so that ArrayA[x][:type] == ArrayB[x][:type] and that you are looking for the maximum between (ArrayA[x], ArrayB[x]) not the entire array. If this is not the case, then other solutions that combine the two arrays will work fine.

 filtered_by_type = ArrayA.zip(ArrayB).select{|x| x[0][:type] == type } filtered_by_type.map {|a| a.max_by {|x| x[:value_length] } } 
0
source

This is how I approached it: you are looking for the maximum of something, so the Array#max method is likely to be useful. You want the actual value in itself, not containing a hash, so this gives us some flexibility. It’s more convenient for you to work with a functional programming style. In my opinion, I see how select , map and max fit together. Here is my solution, which, as indicated, returns the number itself, the maximum value:

 def largest_value_length(type, hashes) # Taking it slowly right_type_hashes = hashes.select{|h| h[:type] == type} value_lengths = right_type_hashes.map{|h| h[:value_length]} maximum = value_lengths.max # Or, in one line #hashes.select{|h| h[:type] == type}.map{|h| h[:value_length]}.max end puts largest_value_length(1, ArrayA + ArrayB) => 8 
0
source

You can also sort after filtering by type. That way you can get the smallest, second largest, etc.

 all = ArrayA + ArrayB all = all.select { |element| element[:type] == 1 } .sort_by { |k| k[:value_length] }.reverse puts all[0][:value_length] #8 puts all[all.length-1][:value_length] #3 
0
source

Source: https://habr.com/ru/post/955527/


All Articles