Home Ruby Array of Arrays returning query to be used for chartjs,
Reply: 2

Ruby Array of Arrays returning query to be used for chartjs,

jeremiah
1#
jeremiah Published in 2018-02-14 02:03:17Z
def self.return_this_data_for_map_method
    data = { :labels => [], datasets: [data: []] }
    dictionary = {}
    results.each do |teams|
        team = teams[0]
        teamMembers = teams[1]

        if dictionary[team].nil?
            dictionary[team] = teamMembers
        else 
            dictionary[team] += teamMembers

        end
    end
    data[:labels] << dictionary.keys
    data[:datasets][0][:data] << dictionary.values
    data
end

This is the data I am getting out

 => {:labels=>[["CUBS", "CARDS", "ROCKIES", "ASTROS"]]:datasets=>[{:data=>[[72, 93, 74, 28]]}]}

This is how I am trying to get my data

=> {:labels=>["CUBS", "CARDS", "ROCKIES", "ASTROS"], :datasets=>[{:data=>[72, 93, 74, 28]}]}

It's wrapping it like it's still in an Array of Arrays, I am not quite seeing how to break how of it. Any suggestions on how I can fix my code would be appreciated.

using ruby 2.3.1

Anthony L
2#
Anthony L Reply to 2018-02-14 03:59:34Z

The simplest solution is to flatten the arrays prior to returning the data:

data = { :labels => [], datasets: [data: []] }
dictionary = {}
results.each do |teams|
    team = teams[0]
    teamMembers = teams[1]

    if dictionary[team].nil?
        dictionary[team] = teamMembers
    else 
        dictionary[team] += teamMembers

    end
end
data[:labels] << dictionary.keys
data[:datasets][0][:data] << dictionary.values
data[:labels].flatten!
data[:datasets][0][:data].flatten!
data
jeremiah
3#
jeremiah Reply to 2018-02-14 20:00:51Z

@maxpleaner and @rails_id were correct

def self.return_this_data_for_map_method
data = { :labels => [], datasets: [data: []] }
dictionary = {}
results.each do |teams|
    team = teams[0]
    teamMembers = teams[1]

    if dictionary[team].nil?
        dictionary[team] = teamMembers
    else 
        dictionary[team] += teamMembers

    end
end
data[:labels] += dictionary.keys
data[:datasets][0][:data] += dictionary.values
data

end

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308812 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO