You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何在filter函数返回两个值?优化现有代码方案

如何在Angular中一次遍历数组同时拆分两组数据?

现有数组allData,需要拆分出service.id === "123"的对象存入bookedServiceData,其余对象存入unbookedServiceData。当前用了两次filter方法实现,希望合并为更高效的单次遍历方案。

最优方案:单次遍历分组(推荐)

使用reduce或forEach只需遍历数组一次,比两次filter的性能更优(时间复杂度从O(2n)降至O(n)),以下是两种实现方式:

方式1:使用Array.reduce(更函数式风格)

private splitServiceData(): void {
  // 初始化累加器,包含两个空数组
  const groupedData = this.allData?.reduce((acc, current) => {
    const isTargetService = current.service?.id === "123";
    isTargetService ? acc.booked.push(current) : acc.unbooked.push(current);
    return acc;
  }, { booked: [], unbooked: [] } as { booked: typeof this.allData; unbooked: typeof this.allData });

  this.bookedServiceData = groupedData?.booked;
  this.unbookedServiceData = groupedData?.unbooked;
}
  • 逻辑:通过reduce的累加器对象,在遍历每个元素时判断归属,将元素推入对应数组,最后一次性赋值给目标变量。

方式2:使用Array.forEach(更直观易懂)

private splitServiceData(): void {
  // 先初始化空数组
  this.bookedServiceData = [];
  this.unbookedServiceData = [];

  this.allData?.forEach(item => {
    if (item.service?.id === "123") {
      this.bookedServiceData.push(item);
    } else {
      this.unbookedServiceData.push(item);
    }
  });
}
  • 逻辑:直接遍历数组,逐个判断元素归属并推入对应数组,代码简洁易读。

对比原方案的优势

原方案调用两次filter会遍历数组两次,当数组元素较多时,单次遍历的方案能明显减少计算开销,提升性能。


内容的提问来源于stack exchange,提问作者user1938143

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 11:30:51