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

按字符串属性值排序JS对象数组,将subscription为ESSENTIAL的账户置顶

JS对象数组按指定规则稳定排序方案

需求说明

给定已完成初步排序的对象数组,需要将type为account且subscription值为ESSENTIAL的元素优先排在最前面,其余所有元素保留原有相对顺序。

实现方案

方案1:ES2019+ 环境(默认稳定排序)

ES2019规范明确要求Array.prototype.sort()为稳定排序,优先级相同的元素会自动保留原有相对顺序,直接按优先级判断即可:

let data = [
  { type: 'account', title: 'Robb', subscription: 'ESSENTIAL' },
  { type: 'account', title: 'Bran', subscription: 'ESSENTIAL' },
  { type: 'account', title: 'Arya', subscription: 'FREE' },
  { type: 'article', title: 'The Wall' },
  { type: 'account', title: 'Tyrion', subscription: 'ESSENTIAL' },
];

const sortedData = data.sort((a, b) => {
  const aIsPriority = a.type === 'account' && a.subscription === 'ESSENTIAL';
  const bIsPriority = b.type === 'account' && b.subscription === 'ESSENTIAL';
  // 优先级高的排前,优先级相同则保持原有顺序
  return bIsPriority - aIsPriority;
});

方案2:全版本兼容(强制稳定排序)

如果需要兼容低版本浏览器,可通过记录原有索引的方式强制保证排序稳定性,避免不同引擎sort实现差异带来的问题:

// 先记录每个元素的原始索引
const indexedData = data.map((item, idx) => ({ ...item, _originIdx: idx }));
const sortedData = indexedData.sort((a, b) => {
  const aIsPriority = a.type === 'account' && a.subscription === 'ESSENTIAL';
  const bIsPriority = b.type === 'account' && b.subscription === 'ESSENTIAL';
  // 优先级不同时按优先级排序
  if (bIsPriority !== aIsPriority) {
    return bIsPriority - aIsPriority;
  }
  // 优先级相同时按原始索引排序,保证原有顺序
  return a._originIdx - b._originIdx;
// 移除临时添加的索引字段
}).map(({ _originIdx, ...rest }) => rest);

最终效果

排序后的数组会把符合条件的3个ESSENTIAL账号按原有顺序排在最前,后续依次是FREE账号的Arya、article类型的The Wall,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:39:05