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

基于下划线分隔的末尾数字对JavaScript数组进行排序

JavaScript数组按末尾下划线后数字升序排序

需求说明

现有如下JavaScript数组:

let arr = [
  '20336.41905.32121.58472_20336.41905.60400.51092_1',
  '20336.41905.32121.58472_20336.41905.60400.48025_2',
  '20336.41905.32121.58472_20336.41905.41816.60719_3',
  '20336.41905.32121.58472_20336.41905.41816.63631_4',
  '20336.41905.32121.58472_20336.41905.31747.22942_2',
];

需要将数组按每个元素下划线分隔后的末尾数字进行升序排序。

实现代码

let arr = [
  '20336.41905.32121.58472_20336.41905.60400.51092_1',
  '20336.41905.32121.58472_20336.41905.60400.48025_2',
  '20336.41905.32121.58472_20336.41905.41816.60719_3',
  '20336.41905.32121.58472_20336.41905.41816.63631_4',
  '20336.41905.32121.58472_20336.41905.31747.22942_2',
];

const sortedArr = arr.sort((a, b) => {
  // 提取每个元素末尾的数字并转为整数
  const numA = parseInt(a.split('_').pop(), 10);
  const numB = parseInt(b.split('_').pop(), 10);
  // 升序排序
  return numA - numB;
});

console.log(sortedArr);

代码逻辑说明

  • 利用数组的sort()方法,传入自定义比较函数实现规则排序
  • 通过split('_')将每个元素按下划线分割为数组,使用pop()获取最后一段(即目标数字字符串)
  • 用parseInt()将字符串转为整数,避免字符串排序的逻辑错误(例如'10'字符串会被判定为小于'2')
  • 返回numA - numB实现升序排序,若需降序则返回numB - numA

排序结果

[
  '20336.41905.32121.58472_20336.41905.60400.51092_1',
  '20336.41905.32121.58472_20336.41905.60400.48025_2',
  '20336.41905.32121.58472_20336.41905.31747.22942_2',
  '20336.41905.32121.58472_20336.41905.41816.60719_3',
  '20336.41905.32121.58472_20336.41905.41816.63631_4'
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:01:23