Most elegant way to fill an Array inside for loop?

Hi,

I am kind of new to the Julia language. I am looking for the most elegant way to fill an Array like in the following code section? (which does not work)

dr = Date(2020,9,12):Day(1):Date(2020,9,18)
openingHours = Array{Time,2}[]
for date in dr
    openingHours = [openingHours; Time(openingHoursYaml[gymName]["open"][Dates.dayname(date)])  Time(openingHoursYaml[gymName]["close"][Dates.dayname(date)])]
end

Since this is inside a function I don’t know in advance how many elements there will be inside dr. This way I cannot create the Array in advance but will need to build it in each iteration.

I hope I can get some good advice here to improove my code.

Best,
Johannes

I find your code a bit hard to read (an expression is possible redundant/repeated?), but you are perhaps looking for comprehensions:

https://docs.julialang.org/en/v1/manual/arrays/#man-comprehensions

2 Likes

Thanks for this suggestion. The comprehension seems like the thing I have been looking for.