Sumodh Nair
Sumodh Nair

Reputation: 1676

Sorting an array based on alphabets?

I need to sort an array based on Alphabets. I have tried sort() method of javascript, but it doesn't work since my array consists of numbers, lowercase letters and uppercase letters. Can anybody please help me out with this? Thanks

For e.g my array is:

[
    "@Basil",
    "@SuperAdmin",
    "@Supreme",
    "@Test10",
    "@Test3",
    "@Test4",
    "@Test5",
    "@Test6",
    "@Test7",
    "@Test8",
    "@Test9",
    "@a",
    "@aadfg",
    "@abc",
    "@abc1",
    "@abc2",
    "@abc5",
    "@abcd",
    "@abin",
    "@akrant",
    "@ankur",
    "@arsdarsd",
    "@asdd",
    "@ashaa",
    "@aviral",
    "@ayush.kansal",
    "@chris",
    "@dgji",
    "@dheeraj",
    "@dsfdsf",
    "@dualworld",
    "@errry",
    "@george",
    "@ggh",
    "@gjhggjghj"
]

Upvotes: 6

Views: 614

Answers (3)

georg
georg

Reputation: 214949

To sort an array by a key function applied to an element (toUpperCase here), Schwartzian transform, aka "decorate-sort-undecorate" is your technique of choice:

cmp = function(x, y) { return x > y ? 1 : x < y ? -1 : 0 }

sorted = array.map(function(x) {
    return [x.toUpperCase(), x]
}).sort(function(x, y) {
    return cmp(x[0], y[0])
}).map(function(x) {
    return x[1]
})

The major advantage of this approach is that the key function is called exactly once for each element, which can matter when the key is heavy or has side effects.

I realize that you're looking for a simple answer right now, but this might be something for you to consider learning in the future.

Upvotes: 1

user2555388
user2555388

Reputation: 41

function alphabetical(a, b){
     var c = a.toLowerCase();
     var d = b.toLowerCase();
     if (c < d){
        return -1;
     }else if (c > d){
       return  1;
     }else{
       return 0;
     }
}


yourArray.sort(alphabetical);

Upvotes: 4

Riri
Riri

Reputation: 11947

a.sort(function(a, b) {
    var textA = a.toUpperCase();
    var textB = b.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});

This should work (jsFiddle)

Upvotes: 7

Related Questions