JavaScript如何实现包含数字和非数字字符的字符串的自然排序

是什么?

        自然排序是一种字符串排序算法,它在排序含有数字的字符串时,能够按照我们人类直观的顺序来排列,而非简单的字典序(即ASCII码顺序)。在标准的字典序排序中,数字会被视为一系列的字符,这会导致一些不符合直觉的排序结果,比如 "file10" 会被排在 "file2" 之前,因为 '1' 的ASCII码小于 '2'。
        自然排序则会识别数字序列,并将其作为一个整体来进行比较。这意味着 "file10" 将会被正确地排在 "file2" 之后,因为在自然排序中,数字 10 实际上大于 2。

代码实现

const testArr = ['file3', 'file1', 'file2', 'file20', 'file10']

const naturalSort = (a, b) => {
  const regex = /(\d+)|(\D+)/g
  const digitsOnly = /^\d+$/
  const aParts = a.match(regex)
  const bParts = b.match(regex)
  for (let i = 0; i < Math.min(aParts.length, bParts.length); i++) {
    const aPart = aParts[i]
    const bPart = bParts[i]
    if (digitsOnly.test(aPart) && digitsOnly.test(bPart)) {
      const aInt = parseInt(aPart, 10)
      const bInt = parseInt(bPart, 10)
      if (aInt !== bInt) {
        return aInt - bInt
      }
    } 
    else if (aPart !== bPart) {
      return aPart.localeCompare(bPart)
    }
  }
  return aParts.length - bParts.length
}

console.log(testArr.sort) // ['file1', 'file10', 'file2', 'file20','file3']
console.log(testArr.sort(naturalSort)) // ['file1', 'file2', 'file3', 'file10','file20']

  • 25
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值