0

I'm having an array arr of maps, for example

arr == [  { pos => [0,0], color => :red, ... },
          { pos => [0,1], color => :green, ...},
          { pos => [1,0], color => :fuchsia, ...},
          { pos => [1,1], color => :red, ...},
          ...
       ]

Where

arr.map { |item| item.pos }

forms a cartesian product of integer ranges [0..n] x [0..m]

I'd gladly access elements by their first coordinate! So use something like

`newArr` == [
              [{ second_coord => 0, color => :red...}, { second_coord => 1, color => :green,...}, .. ],
              [{ second_coord => 0, color => :fuchsia,...}, { second_coord => 1, color => :red, ...},..],
              ...
            ]

Because if I could access it like it, I believe I could redact my code pretty elegantly and readable. If the transformation is short and readable, or at least short. Any hints?

Adrian Panasiuk
  • 7,249
  • 5
  • 33
  • 54

1 Answers1

1

This should do the trick:

new_array = arr.inject([]) |res, e| do 
               res[e.pos[0]] ||= []  # this row maybe not required
               res[e.pos[0]] << {second_coord => e.pos[1], color => e.color } 
            end

You may want to order the inner arrays based on the second_coord but that is simple enough.

Matzi
  • 13,770
  • 4
  • 33
  • 50