我正在尝试将我的多个数组方法调用简化为 if 语句或更简单的基于条件的语句

Posted

技术标签:

【中文标题】我正在尝试将我的多个数组方法调用简化为 if 语句或更简单的基于条件的语句【英文标题】:I am trying to simplify my multiple array method calls into an if statement or something much more simple based on a condition 【发布时间】:2022-01-07 18:21:04 【问题描述】:

我想简化我的代码并拥有一种数组过滤方法,然后根据相应的条件分配 const Alerts,而不是 5 种数组过滤方法。也许一个 if 语句或类似的东西可以解决问题?

    const pendingAlerts = array.filter((a) => a.approval_status === approvalStatuses.pending && !a.canceled_at).sort(sortCommunicationsByDateRule);
    const deniedAlerts = array.filter((a) => a.approval_status === approvalStatuses.denied && !a.canceled_at).sort(sortCommunicationsByDateRule);
    const upcomingAlerts = array.filter((a) => isApproved(a) && !a.canceled_at && a.begin_at > today).sort(sortCommunicationsByDateRule);
    const activeAlerts = array.filter((a) => isApproved(a) && !a.canceled_at && a.begin_at <= today && a.end_at > today).sort(sortCommunicationsByDateRule);
    const expiredAlerts = array.filter((a) => (a.canceled_at || a.end_at < today)).sort(sortCommunicationsByDateRule); 

    
        <div className="comm-communication-list comm-alert-list wrapper">
          this.renderNotificationUI()
          this.renderDefinitionList(pendingAlerts)
          this.renderDefinitionList(upcomingAlerts)
          this.renderDefinitionList(activeAlerts)
          this.renderDefinitionList(deniedAlerts)
          this.renderDefinitionList(expiredAlerts)
        </div> 

  //The ReactJS list above is rendering the Alert variables  i.e.(pending, upcoming, active, denied, and expired)  based upon the robust multiple filter methods 

【问题讨论】:

【参考方案1】:

您可以通过一次遍历输入数组来完成此操作,测试每个条件以包含在其中一个输出数组中。您还可以使用数据将条件与输出数组相关联...

const pendingAlerts = [];
const deniedAlerts = [];
const upcomingAlerts = [];
// and so on...

const criteria = [
  
    array: pendingAlerts,
    criterion: a => a.approval_status === approvalStatuses.pending && !a.canceled_at
  ,
  
    array: deniedAlerts,
    criterion: a => a.approval_status === approvalStatuses.denied && !a.canceled_at
  ,
  
    array: upcomingAlerts,
    criterion: a => isApproved(a) && !a.canceled_at && a.begin_at > today
  ,
  // and so on
];

// this one loop pushes a into each of the output arrays where it matches the criterion
array.forEach(a => 
  criteria.forEach(c => if (c.criterion(a)) c.array.push(a));
);

// then sort the output arrays...
criteriaForEach(c => 
  c.array.sort(sortCommunicationsByDateRule)
);

【讨论】:

以上是关于我正在尝试将我的多个数组方法调用简化为 if 语句或更简单的基于条件的语句的主要内容,如果未能解决你的问题,请参考以下文章

if语句中的奇怪行为

进行GET HTTP调用时Json格式化错误消息

数组中多个 if 语句的 VBA 代码

从 JSON 获取数据并将其格式化为表格

无法使用open()系统调用打开第二个文件

尝试为 Discord bot 提供多个命令文件