tapdancer
tapdancer

Reputation: 389

Add index to element of nested array

I have a nested array:

 [["Area1",["location1", "location2", "location3"]],["Area2",["location4", "location5", "location6"]]]

How do I add an index to the locations in this array so that it will look like:

[["Area1",[["location1",1], ["location2",2], ["location3",3]]],["Area2",[["location4",4], ["location5",5], ["location6",6]]]]

Upvotes: 0

Views: 61

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37419

You need to save the index as a variable, and maintain it as you iterate over the elements:

arr = [["Area1",["location1", "location2", "location3"]],["Area2",["location4", "location5", "location6"]]]

i = 0

arr.each do |area, locations|
  locations.map! { |loc| [loc, i = i + 1] }
end
# => [["Area1", [["location1", 1], ["location2", 2], ["location3", 3]]], ["Area2", [["location4", 4], ["location5", 5], ["location6", 6]]]]

Upvotes: 3

Related Questions