首页 > 解决方案 > 如果条件不满足如何创建新数组?

问题描述

我正在尝试为属于 rxInfo 但与成员 ID 不匹配的 ID 创建数组,但它总是将 memberIds 推送到 mismatchIndexIDs。如何检查该条件是否存在值而不匹配将其推送到数组。

有可能我将在 specialMembers 中有 4 个成员,而 rxInfos 只有 2 个通过。

main.ts

for(const member of specialMembers) {
    for (const rxInfo of this.rxInfos) {
        if (member.indexID === rxInfo.indexID) {
            this.indexIDs.push(rxInfo.indexID);
            proxyMember = member;
            if (!member.dateOfBirth) {
                statusDesc = "member dateOfbirth not found";
                return Promise.reject(this.errorHandler(request, statusDesc));
            }
            const requestBody: any = this.buildSingleRequestBody(proxyMember, rxInfo);
            const requestObject = this.specialtyQuestionRequest(requestBody);
            this.requestArray.push(requestObject);
        } else {
            this.mismatchIndexIDS.push(rxInfo.indexID);
            this.indexIdMismatchCounter++;
        }
    }
}

数据:

 "rxInfos": [
      {
            "drugNdc": "10101",
            "rxNumber": "14556459709",
            "firstFillIndicator": "N",
            "sourceSystem": "TBS",
            "indexID": "RPT0ifQ"
        },
      {
            "drugNdc": "101",
            "rxNumber": "145945000709",
            "firstFillIndicator": "N",
            "sourceSystem": "TBS",
            "indexID": "GJhQ1MrQnZkTFRR"
        }
    ]

    "specialyMembers":[
      {
        "dob":"12-12-1970"
        "firstName": "jimmy",
        "lasteName": "shew",
         "indexID": "RPT0ifQ"
      },
      {
         "dob":"18-10-1970"
        "firstName": "Timmy",
        "lasteName": "Doug",
         "indexID": "GJhQ1MrQ"
      },
        {
         "dob":"17-06-1981"
        "firstName": "John",
        "lasteName": "owascar",
         "indexID": "GJhQ1MrTGDSRQ"
      }
      ]

标签: javascriptarraystypescript

解决方案


不是循环两个数组(O(N^2) 操作),而是将第一个数组转换为由连接键索引的临时对象,然后对第二个数组进行分区。

function partition(arr, predicate) {
    const out = [[],[]];
    arr.forEach(e => out[Number(!!predicate(e))].push(e));
    return out;
}
const membersByIndex = {}
specialMembers.forEach(m => membersByIndex[m.indexID] = m)
const [mismatch, match] = partition(rxInfo, rx => rx.indexID in membersByIndex)

推荐阅读