0

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]]]]

1 Answer 1

3

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]]]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.