There is an array
var sampleArray = ["1","2","3","4","5","6","7","8","9","10"]
there are two elements "header
" and "footer
"
I want to add these two elements such way that after every 3rd index of original array these two are to be appended
Expected Output
sampleArray = ["1","2","3", "header","footer" ,"4","5","6","header","footer""7","8","9""header","footer",10]
I google through the same of the build in methods provided , I found below
insert(_:at:)
But its not serving my purpose, It looks an obvious problem, Is there anybody who created the function like this?
3
Answers
Use new array to proper combine
You can’t just insert into the indices 3, 6, 9 etc, in that order, because after inserting at index 3, the next index to insert at changes (increases by the number of elements you inserted). The third time you insert, it’s been shifted by twice the number of elements you inserted, and so on. If you take this into account, it’s quite simple:
Alternative solution that creates a new array:
The idea here is to
flatMap
certain elements to that element plus the separator, and other elements to themselves.separator
should be added after3
,6
and9
, which are at indices 2, 5, and 8 respectively. Their indices are all one less than a multiple of 3, henceindex % 3 == 2
.The issue is that you are invalidating the indices of your collection when inserting new elements. From the docs
The most simple solution when you need to insert or remove multiple elements is to iterate your collection indices in reverse order:
If you would like to implement your own insert methods:
Usage: