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

JavaScript如何按字符串内嵌的总XP数值对数组排序

JavaScript 按括号内总XP值排序数组实现

核心逻辑是利用数组原生sort()方法,排序前先从每个字符串元素中提取出括号内的总经验数值,转为数字类型后做大小比较。

实现步骤

  • 编写正则匹配规则,定位字符串中(xxx total xp)格式的片段,提取出其中的数字部分
  • 在sort()的比较函数中,分别拿到两个待比较元素的XP数值
  • 返回两个数值的差值作为排序依据,差值为正就交换位置,完成排序

完整可运行代码

const userLevelList = [
  '<@520968882077433856> is level **7,64** _(18115.5 total xp)_',
  '<@289037609274048513> is level **7,07** _(14473 total xp)_',
  '<@672835870080106509> is level **8,25** _(22473.5 total xp)_',
  '<@536686935134175254> is level **6,22** _(10184.5 total xp)_',
];

// 按XP升序排序(经验值从低到高)
const sortedAscList = userLevelList.sort((prev, next) => {
  const prevXp = Number(prev.match(/\(([\d.]+) total xp\)/)[1]);
  const nextXp = Number(next.match(/\(([\d.]+) total xp\)/)[1]);
  return prevXp - nextXp;
});

// 按XP降序排序(经验值从高到低)
const sortedDescList = [...userLevelList].sort((prev, next) => {
  const prevXp = Number(prev.match(/\(([\d.]+) total xp\)/)[1]);
  const nextXp = Number(next.match(/\(([\d.]+) total xp\)/)[1]);
  return nextXp - prevXp;
});

排序结果说明

升序排序后数组元素顺序为:

  • <@536686935134175254> is level **6,22** _(10184.5 total xp)_
  • <@289037609274048513> is level **7,07** _(14473 total xp)_
  • <@520968882077433856> is level **7,64** _(18115.5 total xp)_
  • <@672835870080106509> is level **8,25** _(22473.5 total xp)_

注意事项

  • 提取到的XP值必须转为数字类型再比较,直接用字符串比较会按字典序判定大小,排序结果完全错误
  • 上述正则是基于你给出的固定字符串格式编写的,如果后续字符串中total xp的文案、括号位置发生变化,需要对应调整正则匹配规则
  • sort()会直接修改原数组,如果需要保留原数组顺序,排序前先浅拷贝一份原数组再操作,比如降序示例里用展开运算符做了浅拷贝

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 09:57:16