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

Angular/RXJS如何根据指定字符串值对Observable对象数组排序

解决方法

你可以通过定义分类优先级映射的方式实现自定义排序,完整代码如下:

// 可以定义在组件类的顶部,避免每次流触发时重复创建
private readonly categoryPriority = {
  ONGOING: 0,
  UPCOMING: 1,
  PAST: 2
} as const;

displayCommunityCards$ = this.cardService.displayCards$
  .pipe(
    map(communityEventsCards => 
      // 先拷贝数组再排序,避免修改原数组产生副作用,不需要可以去掉展开运算符
      [...communityEventsCards.filter(community => community.type === 'COMMUNITY EVENT')]
        .sort((a, b) => {
          return this.categoryPriority[a.category] - this.categoryPriority[b.category];
        })
    ),
    tap(data => console.log('Community Cards: ', JSON.stringify(data))),
);

逻辑说明

  • JavaScript的Array.sort()方法接收的比较回调规则为:返回负数时a排在b前,返回正数时b排在a前,返回0时顺序不变
  • 我们给三类category分别赋值从小到大的优先级数字,直接用优先级数值做差,就能刚好匹配你需要的ONGOING > UPCOMING > PAST排序规则
  • 如果需要同分类下再做次级排序(比如同是ONGOING的卡片按开始时间排序),可以在现有排序逻辑基础上补充次级判断:
.sort((a, b) => {
  const priorityDiff = this.categoryPriority[a.category] - this.categoryPriority[b.category];
  // 分类优先级相同时,按开始时间升序排序
  if (priorityDiff === 0) {
    return new Date(a.startTime).getTime() - new Date(b.startTime).getTime();
  }
  return priorityDiff;
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:36:02