Sorting array of string in a specific format A-Z AA-ZZ

扶醉桌前 提交于 2020-08-11 23:59:31

问题


I have a array in javascript like this

[A,AA,CC,DD,B,C]

I want it to be sorted like this

[A,B,C,AA,CC,DD]

回答1:


You can first sort by string length and then alphabetically

var arr = ['A', 'B', 'C', 'AA', 'CC', 'DD'];

var result = arr.sort(function(a, b) {
  return a.length - b.length || a.localeCompare(b)
})
console.log(result)



回答2:


You could sort first by length of the strings and then by value.

var array = ['A', 'AA', 'B', 'C', 'CC', 'DD'];

array.sort(function (a, b) {
    return a.length - b.length || a.localeCompare(b) ;
});

console.log(array);



回答3:


Compare the length of each element - if it's equal - sort it by the first letter.

var str = ['B','A','C','EEE','CCC','AA','DD','CC'],
    res = str.sort(function(a,b) {
      return a.length - b.length || a.charCodeAt(0) - b.charCodeAt(0);
    });
    
    console.log(res);



回答4:


If you want to sort array with the pattern you have mentioned then following code will work you.

        var temp1 = [];
        var temp2 = [];
        var temp3 = [];
        b=['a','c','bb','cc','aa','b'];
        a= b.sort();
        for(i=0;i<a.length;i++)
        {
        temp = a[i];
        if(temp.length == 1)
        {
        temp1.push(temp);
        }
        if(temp.length == 2)
        {
        temp2.push(temp);
        }
        }

        temp3 = $.merge(temp1 ,temp2);

if you are asking about some dynamic function which can sort your string higher than length 2 like [A,B,AA,BB,AAA,BBB] then you have to make it more dynamic.



来源:https://stackoverflow.com/questions/43681099/sorting-array-of-string-in-a-specific-format-a-z-aa-zz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!