I have this code (I'm going to pass it as JSON data for highchart JS)
<%= ItemSale.pluck(:item_id).uniq.map{|item_id| {
name: Item.find(item_id).name,
data: @item_sales.where(item_id: item_id).group_by_day(:date_sold,
format: "%s").count.to_a}}.to_json %>
That returns:
[{"name":"Computer","data":[["1456790400",2],["1456876800",0],["1456963200",1]]},{"name":"Android Phones","data":[["1456876800",3],["1456963200",0],["1457049600",1],["1457136000",0],["1457222400",0],["1457308800",2]]}]
However, I need this:
["1457049600",1]
to be an integer and multiplied to 1000 like this:
[1457049600000,1]
I tried doing sample data to make sure that it is correct and it is working:
@item_sales_series = [{"name":"Computer","data":[[1456790400000,2],[1456876800000,0],[1456963200000,1]]},{"name":"Android Phones","data":[[1456876800000,3],[1456963200000,0],[1457049600000,1],[1457136000000,0],[1457222400000,0],[1457308800000,2]]}].to_json
Is it possible or is there a way to
group_by_day(:date_sold, format: "%s").count.to_a
to output integer instead of string and also multiply it by 1000?
I use the group date gem to group my data by dates. Also I'm not using Highchart gems for this project, I'm trying different approach of inserting data into charts.
>> array = [{"name":"Computer","data":[["1456790400",2],["1456876800",0],["1456963200",1]]},{"name":"Android Phones","data":[["1456876800",3],["1456963200",0],["1457049600",1],["1457136000",0],["1457222400",0],["1457308800",2]]}]
>> array.map{|hash| hash.merge(data: hash[:data].map{|str, int| [str.to_i*1000, int]})}
=> [{:name=>"Computer", :data=>[[1456790400000, 2], [1456876800000, 0], [1456963200000, 1]]}, {:name=>"Android Phones", :data=>[[1456876800000, 3], [1456963200000, 0], [1457049600000, 1], [1457136000000, 0], [1457222400000, 0], [1457308800000, 2]]}]
This works as follows:
# ,-- Loop over every element of the top-level array and change it's value
# | ,-- For each hash, change only the element called "data"
# | | ,-- In the "data" array, change every element
# | | | ,-- Change the string to an integer and multiply by 1000
# | | | |
# v v v v
>> array.map{|hash| hash.merge(data: hash[:data].map{|str, int| [str.to_i*1000, int]})}