Search code examples
javascriptrubyarrayshashrickshaw

How to convert an array of integers into x/y coordinates for rickshaw


I'm trying to integrate the awesome JS graphing library Rickshaw into my project. Rickshaw can be found here: http://code.shutterstock.com/rickshaw/

The data that I want to graph is in a simple array:

data = [51929, 65932, 49119, 50379, 103501, 92430, 93107, 105710, 115200, 109283]

I would like to use the index of each element in the array as the x coordinate, and the element itself as the y coordinate. I need to format this into something like the following format so Richshaw can do its magic:

data = [ { x: 0, y: 40 }, { x: 1, y: 49 }, { x: 2, y: 17 }, { x: 3, y: 42 } ];

I've tried various methods, the closest I have come is to produce an array of quotes with the hashes inside, like so:

clean_data = []
data.each_with_index do |value, index|
  clean_data << "{x: #{index}, y: #{value} }”
end 
clean_data.to_a

which returns:

["{x: 0, y: 51929}", "{x: 1, y: 65932}", "{x: 2, y: 49119}" ... etc...]

So my question is either, how can I remove the quotes in the above to get just an array of hashes, or, if I'm on the wrong track: how can I format the array to make it presentable to Rickshaw? I'd prefer to work with Ruby here, but anything in JavaScript would be great as well.

Thanks.


Solution

  • You were pretty close. Try this:

    data = [51929, 65932, 49119, 50379, 103501, 92430, 93107, 105710, 115200, 109283]
    clean_data = []
    data.each_with_index do |value, index|
      clean_data << {:x => index, :y => value}
    end 
    
    clean_data.to_json