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"
]
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.
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.
To sort an array of strings in Java, we can use Arrays. sort() function.
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.
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With