Antonio Craveiro
Antonio Craveiro

Reputation: 121

How to iterate through an array where each iteration is a subarray instead of an element

In my example I want to iterate over an array of days that represents a Month and on each iteration work over a week. But the question can be generalized for many situations.

I was trying to do it with subArrays using Array.copyOfRange but can't make it work

Some pseudo code of what I want

for(aWeek in rangeOfSubarraysOfMonth)
   //do stuff

Upvotes: 1

Views: 238

Answers (1)

Rinat Suleimanov
Rinat Suleimanov

Reputation: 517

Would this example work for you?

Assuming, that val months: Array<Array<Day>>

    months
        .flatten()    //convert to list of days
        .chunked(7)   //chunk by 7 days 
        .forEach { week ->
            println("${week[0]}  is Monday")
            println("${week[1]}  is Tuesday")
            println("${week[2]}  is Wednesday")
            println("${week[3]}  is Thursday")
            //etc.
        }

Upvotes: 2

Related Questions