在JavaScript中对混合的字母/数字数组进行排序 [英] Sort mixed alpha/numeric Array in javascript

查看:58
本文介绍了在JavaScript中对混合的字母/数字数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var x = ['1','2A','2B','2AA','2','10A','10','11','12A','12B','12']

所需的输出

sortedArray = ['1','2','2A','2B','2AA','10','10A','11','12','12A','12B']

我曾经尝试过使用lodash,但没有得到想要的结果

var x = ['1','2A','2B','2AA','2','10A','10','11','12A','12B','12']

_.sortBy(x);

//lodash result

 ["1", "10", "10A", "11", "12", "12A", "12B", "2", "2A", "2AA", "2B"]

推荐答案

您可以使用 localeCompare

You can use parseInt to get the number part and sort it. If both a and b have the same number, then sort them based their length. If they both have the same length, then sort them alphabetically using localeCompare

let array = ['1','2A','2B','2AA','2','10A','10','11','12A','12B','12'];

array.sort((a, b) => parseInt(a) - parseInt(b) 
                  || a.length - b.length 
                  || a.localeCompare(b));
                  
console.log(array)

这篇关于在JavaScript中对混合的字母/数字数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆