Waqas Javed
Waqas Javed

Reputation: 39

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

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]

Upvotes: 1

Views: 1629

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386550

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

Upvotes: 4

Ekta Dobaria
Ekta Dobaria

Reputation: 13

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.

Upvotes: 0

kind user
kind user

Reputation: 41893

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

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122027

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)

Upvotes: 7

Related Questions