Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Short answer:</p> <pre><code>h = Hash.new 0 product_list.each {|p| h[p] += 1} product_list_result = h.keys.map{|k| k["count"] = h[k]; k} </code></pre> <p>Longer answer explaining how this works. Starting with your data:</p> <pre><code>product_list = [ { "product" =&gt; 1, "x" =&gt; 200, "y" =&gt; 100, "z" =&gt; 18}, { "product" =&gt; 1, "x" =&gt; 200, "y" =&gt; 100, "z" =&gt; 18}, { "product" =&gt; 1, "x" =&gt; 300, "y" =&gt; 100, "z" =&gt; 18}, { "product" =&gt; 2, "x" =&gt; 300, "y" =&gt; 100, "z" =&gt; 18}, { "product" =&gt; 2, "x" =&gt; 100, "y" =&gt; 100, "z" =&gt; 18}, { "product" =&gt; 2, "x" =&gt; 100, "y" =&gt; 100, "z" =&gt; 18}, { "product" =&gt; 3, "x" =&gt; 100, "y" =&gt; 100, "z" =&gt; 18} ]; # First, create a hash to count the number of unique products. Have the initial # count be 0. h = Hash.new 0 # Add each product to the hash count. product_list.each {|p| h[p] += 1} </code></pre> <p>Now you have a hash with products as keys, and counts as values:</p> <pre><code>h = {{"z"=&gt;18, "y"=&gt;100, "x"=&gt;100, "product"=&gt;3}=&gt;1, {"z"=&gt;18, "y"=&gt;100, "x"=&gt;300, "product"=&gt;1}=&gt;1, {"z"=&gt;18, "y"=&gt;100, "x"=&gt;200, "product"=&gt;1}=&gt;2, {"z"=&gt;18, "y"=&gt;100, "x"=&gt;300, "product"=&gt;2}=&gt;1, {"z"=&gt;18, "y"=&gt;100, "x"=&gt;100, "product"=&gt;2}=&gt;2} </code></pre> <p>Now convert it to the array format you desire:</p> <pre><code>product_list_result = [] h.keys.each do |k| # since each key is a product hash, we can add count to it k["count"] = h[k] # Now, add that to the array product_list_result &lt;&lt; k end </code></pre> <p>Which results in:</p> <pre><code>product_list_result = [ {"z"=&gt;18, "y"=&gt;100, "x"=&gt;100, "product"=&gt;3, "count"=&gt;1}, {"z"=&gt;18, "y"=&gt;100, "x"=&gt;300, "product"=&gt;1, "count"=&gt;1}, {"z"=&gt;18, "y"=&gt;100, "x"=&gt;200, "product"=&gt;1, "count"=&gt;2}, {"z"=&gt;18, "y"=&gt;100, "x"=&gt;300, "product"=&gt;2, "count"=&gt;1}, {"z"=&gt;18, "y"=&gt;100, "x"=&gt;100, "product"=&gt;2, "count"=&gt;2} ] </code></pre> <p>The array conversion can be done more succinctly:</p> <pre><code>product_list_result = h.keys.map{|k| k["count"] = h[k]; k} </code></pre> <p>h.keys returns an array of keys from hash h, which is just the unique products in your list. The function map then replaces each object in that array with the result of the block that follows which simply adds the count value to the product hash.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload