javascript - 如果条件不满足如何创建新数组?
问题描述
我正在尝试为属于 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"
}
]
解决方案
不是循环两个数组(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)
推荐阅读
- bitcoin - 比特币现金 bitcoin-cli 无法连接到 RPC 服务器
- unity3d - 在 Admob 中完成激励视频广告后,文本未更改
- python - 从插入查询中获取数据?
- wpf - 在 WPF 的 ListView 中将 ComboBox 放在一个特殊的行中
- mysql - 如何通过 bash 创建新的 mysql 数据库/模式?
- javascript - 如何以编程方式访问 vuetify 元素的属性?
- amazon-web-services - 扫描 DynamoDB 并过滤具有空数组值的项目
- javascript - 使用 JS 浏览网站文件服务器端?
- java - 我可以将 JSON-LD 转换为 Java 对象吗?
- azure-ad-b2c - 在 Google 注册过程中在 AAD B2C 中编写自定义属性