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

如何在JavaScript中仅依据数字部分对字母数字混合数组进行排序

JavaScript 实现混合字符串按内部数字排序

实现代码

// 原始数组
const originArr = ['state1035', 'dm5', 'state123', 'county247', 'county2']

// 排序逻辑
const sortedArr = originArr.sort((prev, next) => {
  // 提取两个元素中的连续数字片段,转成十进制整数
  const prevNum = parseInt(prev.match(/\d+/)[0], 10)
  const nextNum = parseInt(next.match(/\d+/)[0], 10)
  // 按数字大小升序排列
  return prevNum - nextNum
})

// 输出结果:['county2', 'dm5', 'state123', 'county247', 'state1035']
console.log(sortedArr)

逻辑说明

  • 正则/\d+/用于匹配字符串中连续的数字字符,match()方法返回的数组第0项就是匹配到的完整数字字符串
  • 用parseInt()将数字字符串转成十进制整数,避免字符串按位排序导致的'1035' < '2'错误
  • sort()方法的比较函数返回两个数字的差值,即可实现按数字大小的升序排列

如果业务场景中存在不带数字的元素,可以给匹配逻辑加兜底值避免报错:

// 兜底写法,无数字的元素默认排在最前面
const prevNum = parseInt(prev.match(/\d+/)?.[0] || 0, 10)
const nextNum = parseInt(next.match(/\d+/)?.[0] || 0, 10)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:12:03