如果条件不满足,如何创建新数组?

时间:2018-11-26 22:16:45

标签: javascript arrays typescript

我正在尝试为rxInfo的一部分但不与成员ID匹配的ID创建数组,但是它总是将memberId推送到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"
      }
      ]

1 个答案:

答案 0 :(得分:0)

与其在两个数组上循环(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)