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,保证无数字项在同组排序中处于最前位置。 - 组名逆序:通过
groupB.localeCompare(groupA)实现组名从Z到A的逆序排列。 - 同组数字逆序:利用
numB - numA的差值排序,数字大的项会排在前面,无数字项因num值为-1,会被优先排列。
内容的提问来源于stack exchange,提问作者Ruslan Vyvdyuk
相关产品推荐
相关产品推荐

