在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)