What is the best way to accomplish this in Ruby? Array1 contains few numbers Array2 contains unsorted numbers. We want to find out how often each element of Array1 shows up in Array2.
Example:
Array1 = [0,1,2,3]
Array2 = [0,0,0,3,3,3,2,1,0,3,6,1,3]
Result = {"0"=>4, "1"=>2, "2"=>1, "3"=>5}
Is there a better optimal way to do this than:
- picking each element of
Array1 - iterating over
Array2 - incrementing a counter each time elements match
Example just shows few number but I want to find out best way to do this for a very large array set.
You can use
group_byto count the items inarray2:If you want, you can then extract the sub-hash with the keys from
array1(but I don’t think this is really necessary):