Order in Invoice Line Items

Order in Invoice Line Items

We have written a script where we are adding some items in the invoice if custom function is initiated. Fo example:

Items Qty
A      3
B      2

Will look like

Items Qty(Desired Format)
A      3      
X      3
Y      3
B      2
X      2
Y      2

But while running the script the invoice is uptated as:

items      Qty(Actual Format)
A      3
B      2
X      3
Y      3
X      2
Y      2


How can i add the items in the invoice as the desired format. Attaching our script for your reference. Let us know if how can we proceed.