Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array based on alphabets?

Tags:

javascript

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"
]
like image 668
Sumodh Nair Avatar asked Jul 08 '13 09:07

Sumodh Nair


People also ask

How do you sort an array in alphabetical order?

The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.

How do you sort a string in alphabetical order?

Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.

How would you sort an array of strings?

To sort an array of strings in Java, we can use Arrays. sort() function.

How do you sort an array in alphabetical order in Python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.


2 Answers

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)

like image 51
Riri Avatar answered Sep 29 '22 08:09

Riri


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);
like image 20
user2555388 Avatar answered Sep 29 '22 08:09

user2555388