The IN1 Segments can be reordered by using a treeMap object type. Here is the code with comments to accomplish this.
// Get IN1 segements
var in1Count = message.getCount('IN1');
// populate treemap with segments. The key will autosort in a key map
var in1Map = new java.util.TreeMap();
for (var i = 1; i <= in1Count; i++) {
//get the field we wish to order by. In this case it is in1 -22
var order = message.getNode('IN1-22', i) * 100;
//Verify there is not a duplicate. If so add 1 to it to make the key unique
while (in1Map.get(order) !== null) {
order++;
}
//add the in1 segment to the treemap. The order is a number and the treemap will order by that number.
in1Map.put(order, message.getNode('IN1', i));
}
// remove all IN1 segments
message.removeAllNodes('IN1');
// Create array from treemap
var in1Array = in1Map.entrySet().toArray();
// iterate map and write new IN1 segments by key order
for (var j=in1Array.length-1; j >= 0; j--) {
var segment = qie.parseHL7String(in1Array[j].getValue());
segment.setNode('IN1-1', (j+1));
message.addChildAfter('PV1', 'IN1', segment.getNode('/'));
}