stevec
stevec

Reputation: 52238

Add elements of an array to a specific index of each array within an array of arrays

I have an array of arrays that serves as a table of data, and am trying to add an extra array as though adding an extra column to the table.

For simplicity, suppose the first array is a

a = [["a", "b", "c"], ["e", "f", "g"], ["i", "j", "k"]]

and the second array is b

b = ["d", "h", "l"]

the desired output is:

c = [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"]]

I have tried using + and some attempts at using map but cannot get it

Upvotes: 0

Views: 121

Answers (3)

SteveTurczyn
SteveTurczyn

Reputation: 36860

You can zip them together which will create array elements like [["a", "b", "c"], "d"] and then just flatten each element.

a.zip(b).map(&:flatten)
#=> [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"]]

Answer improved as per Cary's comment. I think he's done Ruby stuff before.

Upvotes: 5

mrzasa
mrzasa

Reputation: 23307

You can use #each_with_index combined with #map to iterate over the array a and append respective elements of array b

> a.each_with_index.map{|e, i| e | [b[i]] }
=> [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"]]

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110675

a.zip(b).map { |arr,e| arr + [e] }
  #=> [["a", "b", "c", "d"],
  #    ["e", "f", "g", "h"],
  #    ["i", "j", "k", "l"]]

The intermediate calculation is as follows.

a.zip(b)
  #=> [[["a", "b", "c"], "d"],
  #    [["e", "f", "g"], "h"],
  #    [["i", "j", "k"], "l"]]

See Array#zip.

Upvotes: 4

Related Questions