Thet are two layer merge methods:
merge() ArtLayer Merges the layer down, removing the layer from the document; returns a reference to the art layer that this layer is merged into. The current and one layer down. of course you can use several merge(); merge(); merge(); merge(); merge();
mergeVisibleLayers () Flattens all visible layers in the document. Only the visible ones so you can controll which layers will be merged using layer visibility.
I try it this way implement
And as the Layer’s Index should be an indicator of its position in the Layer stack it should be possible to determine how many merges it would take.
But Groups and Adjustment Layers may necessitate to progress from the lowest Layer up and not from the selected now down.