Set filter on sub grid using FetchXML

AP.Contact.FilterGrid = function (eContext)
{
    const formContext = eContext.getFormContext();
    let formType = formContext.ui.getFormType();
    let recordId = formContext.data.entity.getId();

    if (formType !== 1 && recordId !== null)
    {
        recordId = recordId.replace('{', '').replace('}', '')
        var fetchXml = "<filter type='or'><condition attribute='ap_primaryserviceuserid' operator='eq' value='" + recordId + "' /><condition attribute='ap_secondaryserviceuserid' operator='eq' value='3F42B6A5-C63B-EC11-8C62-000000000000' /></filter>";
        Common.Actions.FilterSubGrid(eContext, "grid name", fetchXml);
    }
}

Add following to common.actions

// Function to filter a subgrid
Common.Actions.FilterSubGrid = function (eContext, gridName, fetchXML) {

    var formContext = eContext.getFormContext();

    // Get grid control
    var gridContext = formContext.getControl(gridName);

    // Set filter
    gridContext.setFilterXml(fetchXML);

    // Refresh filter
    gridContext.refresh();

}

Note : In order for this to work, untick “Related Records Only” so all records are displayed and then use above filter