简体   繁体   English

在JavaScript中对混合的字母/数字数组进行排序

[英]Sort mixed alpha/numeric Array in javascript

I have a mixed array that I need to sort by digit and then by alphabet 我有一个混合数组,需要按数字然后按字母排序

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

Desired Output 期望的输出

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

I had tried using lodash but wasn't getting desired result 我曾尝试使用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"]

You can use parseInt to get the number part and sort it. 您可以使用parseInt获取数字部分并对其进行sort If both a and b have the same number, then sort them based their length . 如果ab的编号相同,则根据其length对它们进行排序。 If they both have the same length, then sort them alphabetically using localeCompare 如果它们的长度相同,则使用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) 

You can use custom sot function, within custom function split digit and non-digit seperately and sort based on num and if both are equal compare the non-digit part. 您可以使用自定义sot函数,在自定义函数中分别将数字和非数字分开,并基于num进行排序,如果两者相等,则比较非数字部分。

 const arr = ['1', '2A', '2B', '2AA', '2', '10A', '10', '11', '12A', '12B', '12'] arr.sort((a, b) => { // extract digit and non-digit part from string let as = a.match(/(\\d+)(\\D*)/); let bs = b.match(/(\\d+)(\\D*)/); // either return digit differennce(for number based sorting) // in addition to that check string length(in case digits are same) // or compare non-digit part(string comparison) return as[1] - bs[1] || a.length - b.length ||as[2].localeCompare(bs[2]); }) console.log(arr) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM