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

Typescript如何对含父子关系的Edition对象数组按多条件排序

实现方案

你可以采用「先分组、再排序、最后拼接」的逻辑实现需求,比在单个sort比较函数中写复杂判断的可读性更高,也更容易后期维护,完整实现代码如下:

export interface Edition {
  name: string;
  edition_code: string;
  parent_code: string;
  released_at: number;
}

this.dataSource = this.editionService.allEditions().pipe(
  map((editions) => {
    // 按parent_code分组存储子版本
    const childGroup = new Map<string, Edition[]>()
    const parentEditions: Edition[] = []

    editions.forEach(edition => {
      // 父版本单独归集
      if (!edition.parent_code) {
        parentEditions.push(edition)
        return
      }
      // 子版本按所属父版本的edition_code分组
      if (!childGroup.has(edition.parent_code)) {
        childGroup.set(edition.parent_code, [])
      }
      childGroup.get(edition.parent_code)!.push(edition)
    })

    // 所有父版本按发布时间倒序排列
    parentEditions.sort((a, b) => b.released_at - a.released_at)

    const sortedResult: Edition[] = []
    parentEditions.forEach(parent => {
      // 先加入父版本本身
      sortedResult.push(parent)
      // 取出对应子版本,按name字段字母序排序后追加
      const children = childGroup.get(parent.edition_code) || []
      children.sort((a, b) => a.name.localeCompare(b.name))
      sortedResult.push(...children)
    })

    return sortedResult
  })
)

适配提示

如果你的实际业务数据中released_at为字符串格式的时间戳,只需将父版本排序逻辑修改为以下代码即可兼容:

parentEditions.sort((a, b) => Number(b.released_at) - Number(a.released_at))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 17:45:03