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

TypeScript中按active、location双字段排序列表失效如何解决

TypeScript 自定义分组排序实现方案

原代码失效原因

你之前写的排序逻辑存在两个核心问题:

  • 没有提前提取active: true项对应的location值,无法识别需要紧跟在active项后的同location分组
  • 比较函数中location判断逻辑不符合Array.sort的规则:相等返回1、不等返回-1的写法会打乱同组元素顺序,无法实现稳定分组。

Array.sort比较函数的规则是:返回值小于0时a排在b前,大于0时b排在a前,等于0时相对位置不变。

正确实现逻辑

排序按三级优先级执行:

  1. 最高优先级:active: true的项固定置顶
  2. 次高优先级:所有location值和active项location一致的非active项,紧跟在active项之后
  3. 最低优先级:剩余非active项按location值升序排列,同location值的项自动相邻分组

可直接运行的代码

// 提前获取active项的location值
const targetActiveLocation = productList.find(item => item.active)?.location;

productList.sort((a, b) => {
  // 第一排序规则:active项置顶
  if (a.active !== b.active) {
    return a.active ? -1 : 1;
  }
  // 第二排序规则:同active项location的组优先
  const aIsTargetGroup = a.location === targetActiveLocation;
  const bIsTargetGroup = b.location === targetActiveLocation;
  if (aIsTargetGroup !== bIsTargetGroup) {
    return aIsTargetGroup ? -1 : 1;
  }
  // 第三排序规则:剩余项按location升序分组
  return a.location - b.location;
});

执行上述代码后,输出结果和你给出的预期结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 23:36:27