Sort an Array alphabetically when each number is converted into words | Variable to store the word form of units digit and up to twenty ; Variable to store the word form of tens digit ; Function to convert a two digit number to the word by using the above defined arrays ; If n is more than 19 , divide it ; If n is non - zero ; Function to print a given number in words ; Stores the word representation of the given number n ; Handles digits at ten millions and hundred millions places ; Handles digits at hundred thousands and one millions places ; Handles digits at thousands and tens thousands places ; Handles digit at hundreds places ; Call the above function to convert the number into words ; Function to sort the array according to the albhabetical order ; Vector to store the number in words with respective elements ; Inserting number in words with respective elements in vector pair ; Sort the vector , this will sort the pair according to the alphabetical order . ; Print the sorted vector content ; Driver Code
var one = [ " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " ] ; var ten = [ " " , " " , " " , " " , " " , " " , " " , " " , " " , " " ] ; function numToWords ( n , s ) { var str = " " ; if ( n > 19 ) str += ten [ Math . floor ( n / 10 ) ] + one [ n % 10 ] ; else str += one [ n ] ; if ( n ) str += s ; return str ; } function convertToWords ( n ) { var out ; out += numToWords ( Math . floor ( n / 10000000 ) , " " ) ; out += numToWords ( ( Math . floor ( n / 100000 ) % 100 ) , " " ) ; out += numToWords ( ( Math . floor ( n / 1000 ) % 100 ) , " " ) ; out += numToWords ( ( Math . floor ( n / 100 ) % 10 ) , " " ) ; if ( n > 100 && n % 100 ) out += " " ; out += numToWords ( ( n % 100 ) , " " ) ; return out ; } function sortArr ( arr , n ) { var vp = new Array ( n ) ; for ( var i = 0 ; i < n ; i ++ ) { vp [ i ] = [ convertToWords ( arr [ i ] ) , arr [ i ] ] ; } vp . sort ( ) ; for ( var i = 0 ; i < n ; i ++ ) document . write ( vp [ i ] [ 1 ] + " " ) ; } var arr = [ 12 , 10 , 102 , 31 , 15 ] ; var n = arr . length ; sortArr ( arr , n ) ;