This can very quickly become very complicated, but Ill bulletpoint it and hopefully it helps.
1 check the lenght of the array used, and here decide on how manny pages you want to spawn and set a reference for it, allso create a reference on the total number of items to be spawned and is currently spawned.
2 do a for loop for as manny number of pages you want to spawn using previously set pages ref.
3 inside that foor loop you check the number of items to be spawned, using the saved item ref and created items ref.
4 create another for loop as long as the number of items you want to spawn.
5 loop it and spawn the items.
save how manny items that were created. //loop 3 untill done
//loop 2 untill done
profit