Thursday, October 6, 2016

Alphanumeric Sorting in JavaScript using sort function


Sorting using sort() function in JavaScript


Function sort() is basically used for sorting an array in JavaScript.

Let us take few sample codes and see how this function behaves with arrays of different types of elements such as numbers , strings , alphanumeric etc.

Example 1: 
var ar = [11,23,7,189,9,550];
var result = ar.sort();
console.log(result);

Output: [ 11, 189, 23, 550, 7, 9 ]
  • Conclusion : The above example sorts the array of Numbers is lexical / dictionary order.

Example 2: 
var ar = [11,23,7,189,9,550];
var result = ar.sort(numberic_sort);
console.log(result);

//This function cannot be used for string comaprision
function numberic_sort(a,b){
return a-b;
};

Output : [ 7, 9, 11, 23, 189, 550 ]
  • Conclusion : The above customized function sorts the array of numbers in ascending order.

Example 3:
var ar = ["as","asddd","trhs","oocww","wfewf","kcnw","qmdkvcn","acwwev"];
var result = ar.sort();
console.log(result);

Output: 
'acwwev',
'as',
'asddd',
'kcnw',
'oocww',
'qmdkvcn',
'trhs',
'wfewf' ]
  • Conclusion : The above example sorts the array of Strings is lexical / dictionary order.

Example 4:
var ar = ["csnc33","cddsc1","cwew91","fdwef62","vc2211","2831nb1","7dsv7sv","ncnd777","22nbebe","ewfwef873bttbbbbbgc","fdwef69","fdwef61","123","njahy","125","0.342"];
var result = ar.sort();
console.log(result);

Output : [
'0.342',
'123',
'125',
'22nbebe',
'2831nb1',
'7dsv7sv',
'cddsc1',
'csnc33',
'cwew91',
'ewfwef873bttbbbbbgc',
'fdwef61',
'fdwef62',
'fdwef69',
'ncnd777',
'njahy',
'vc2211' ]
  • Conclusion : The above example also sorts the array of Strings is lexical / dictionary order.

Example 5:
var ar = ["A","a","1",1,"cascsac","cccead","treave","mvwen","VV344FFVveve323","v8e8v98vvd","3234223","3332csdvv3","323","3451","68564","11243","562",45,2352,255,0.432,64.223,"5545.454"];
var result = ar.sort();
console.log(result);

Output : 
0.432,
1,
'1',
'11243',
2352,
255,
'323',
'3234223',
'3332csdvv3',
'3451',
45,
'5545.454',
'562',
64.223,
'68564',
'A',
'VV344FFVveve323',
'a',
'cascsac',
'cccead',
'mvwen',
'treave',
'v8e8v98vvd' ]

Conclusion: 
  • By default ,All the values are compared as strings in sort function , hence sorting is in lexical/dictionary order.
  • Sorting Order :  numbers -> capital Alphabets -> small alphabets
  • Example  :  [1, "1", "1a", "A" ,"a", "b1"]  (Ascending order) 

Let us take Some more example , but now with Comparison Operators such as  > , <  , == etc


  • 1 < 2 true
  • "1" < "2"  true
  • "1" == 1  true
  • "1" < "a"   true
  • "1" < "sacacasc"  true
  • "0.3" < "svs"  true
  • "sscsd" < "sscsd8776"  true

As you can see from above examples that comparison operator also woks similar as sort function.
It also compares values as strings and hence gives results according to lexical order. 

1 comment: