Custom function to sort string array in JavaScript

JavaScript provides an inbuilt function sort() to sort the elements inside an array.

For example.

Let us consider the following array

var numbers=[5,3,6,2,7,1];

We can easily sort it using sort() method.


output – [1,2,3,5,6,7]

Same will be case in case the arrays is made up of string elements.

var str=[‘a’,’g’,’t’,’a’,’b’];

output – [ ‘a’,’a’,’b’,’g’,’t’ ]

But in case your array also contains uppercase letters like this

var str=[‘a’,’g’,’t’,’a’,’b’,’A’,’H’];

the output of this method after applying the sort() function will be [ ‘A’,’H’,’a’,’a’,’b’,’g’,’t’ ], which we didn’t expect to see. The reason output is such is because sort() function compares the ASCII values of the elements and since ASCII value of ‘H’ is less than ‘a’, so it be considered less than ‘a’. To properly sort it on the basis of characters we can create our own method or rather overwriting the already present sort() method.

var a1=a.toLowerCase(), b1=b.toLowerCase(); //convert characters to lowercase
if(a1<b1) return -1;
if(a1>b1) return 1;
return 0;

and now if you see the result after sorting, it will be like this.

[ ‘A’,’a’,’a’,’b’,’g’,’H’,’t’ ]

Related Posts

Leave a Reply