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

JavaScript对象数组特殊逆序排序问题求解

特殊规则的数组排序实现方案

原始数组

const arr = [
  { name: "Exhibit A" }, 
  { name: "Exhibit A1" }, 
  { name: "Exhibit A2" }, 
  { name: "Exhibit B" }, 
  { name: "Exhibit C" }, 
  { name: "Exhibit C1" },  
  { name: "Exhibit C2" }, 
  { name: "Exhibit C3" }, 
]

排序需求

需要实现特殊逆序排序,规则如下:

  • 整体按组名逆序排列(如C组优先于B组、A组)
  • 同组内无数字的项(如Exhibit C)排在该组首位
  • 同组内带数字的项按数字逆序排列(如C3 > C2 > C1)

期望结果

const result = [
  { name: "Exhibit C" }, 
  { name: "Exhibit C3" }, 
  { name: "Exhibit C2" }, 
  { name: "Exhibit C1" },
  { name: "Exhibit B" }, 
  { name: "Exhibit A" }, 
  { name: "Exhibit A2" }, 
  { name: "Exhibit A1" }
]

问题分析与修正方案

你之前的代码存在两处逻辑问题:一是同组数字项的判断条件重复,导致排序逻辑失效;二是无数字项的排序逻辑错误,无法确保其排在组内首位。以下是修正后的实现:

const result = [...arr].sort((a, b) => {
  // 提取组名和数字部分,正则精准匹配格式
  const matchA = a.name.match(/Exhibit\s([A-Z])(\d*)/);
  const matchB = b.name.match(/Exhibit\s([A-Z])(\d*)/);
  
  const groupA = matchA[1];
  const groupB = matchB[1];
  // 无数字项赋值为-1,确保在同组内排序时优先级最高
  const numA = matchA[2] ? parseInt(matchA[2], 10) : -1;
  const numB = matchB[2] ? parseInt(matchB[2], 10) : -1;

  // 先按组名逆序比较
  if (groupA !== groupB) {
    return groupB.localeCompare(groupA);
  }

  // 同组内按数字逆序排列,无数字项自然排在首位
  return numB - numA;
});

代码逻辑说明

  1. 正则提取优化:直接抓取组名(单个大写字母)和数字部分,数字为空时转为-1,保证无数字项在同组排序中处于最前位置。
  2. 组名逆序:通过groupB.localeCompare(groupA)实现组名从Z到A的逆序排列。
  3. 同组数字逆序:利用numB - numA的差值排序,数字大的项会排在前面,无数字项因num值为-1,会被优先排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:35:29