JavaScripting in Mirth – Ignore DG1 segments Until Condition Is Met

DG1|1||Z3800^Single liveborn infant, delivered vaginally^I10|||A|||||||||||||||||||||
DG1|2||Z23^Encounter for immunization^I10|||S||||||||||||||||||||E|
DG1|3||A3800^Single liveborn infant, delivered vaginally^I10|||P||||||||||||||||||||E|
DG1|4||B3800^Single liveborn infant, delivered vaginally^I10|||S||||||||||||||||||||E|

The above message sample is formatted in a way that I only want to start reading the values of DG1 when DG1.6 = P. And then read in the DG1 segments after when DG1.6 is P. In the above example, I want to ignore DG1|1, DG1|2 and then only store the values of DG1|3 and DG1|4. I tried using localeCompare but soon realized that doesn’t look like what I can easily use. I also tried assigning A, P, and S numerical values to compare which I think will work (essentially adding |1|+1 when A = 1, |2|+2 when S = 2, etc. But I feel like I’m complicating it.

DG1 is a dynamic set in HL7 so it can be of any length.

Here’s my current code set that will ignore DG1 segment when DG1.6 is “A”.

var dxXML = '';
var dg1Count = msg['DG1'].length();

for (var i = 0; i < dg1Count; i++) {
    var dx;
    var poa;

    if (msg['DG1'][i] != undefined) {
        if (msg['DG1'][i]['DG1.6']['DG1.6.1'].toString() == 'A' || msg['DG1'][i]['DG1.6']['DG1.6.1'].toString() == 'ADMITTING') {
            //format: <Dx Code="${dx0}" POA="${poa0}" Pos="1"/>
            dx = '';
            poa = '';
            if (dxXML != '') {
                dxXML = dxXML + 'n<Dx Code="' + dx + '" POA="' + poa + '" Pos="' + i + '"/>';
            } else {
                dxXML = '<Dx Code="' + dx + '" POA="' + poa + '" Pos="' + i + '"/>';
            }
        }
        //normal dx. the first non-blank dx will be imported as PDX. This means the i can be any integer.
        else {
            dx = msg['DG1'][i]['DG1.3']['DG1.3.1'].toString();
            poa = msg['DG1'][i]['DG1.26']['DG1.26.1'].toString();
            
            if (dx == '') continue;
            if (poa == 'E' || poa == '') {
                poa = '1'; 
            }       
    
            if (dxXML != '') {              
                dxXML = dxXML + 'n<Dx Code="' + dx + '" POA="' + poa + '" Pos="' + i + '"/>';
            } else {                    
                dxXML = '<Dx Code="' + dx + '" POA="' + poa + '" Pos="' + i + '"/>';
            }
        }
    }
    else {
        //do nothing to not add the blank ones.
    }
}
$c('DX_DOM', dxXML);

Any guidance on how to accomplish this will be appreciated.