Alphabet-based array sorting?

I need to sort an array based on Alphabets. I tried the javascript sort () method, but it does not work, since my array consists of numbers, lowercase letters and uppercase letters. Can someone please help me with this? Thanks

For example, my array:

[ "@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" ] 
+6
source share
3 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)

+7
source
 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); 
+4
source

To sort an array by the key function applied to the element ( toUpperCase here), the Schwartz 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 main advantage of this approach is that the key function is called exactly once for each element, which can make a difference when the key is heavy or has side effects.

I understand that you are looking for a simple answer right now, but it may be something for you to consider learning in the future.

+1
source

Source: https://habr.com/ru/post/948925/


All Articles