Sort numbers based on count of letters required to represent them in words | letters [ i ] stores the count of letters required to represent the digit i ; Function to return the sum of letters required to represent N ; Function to sort the array according to the sum of letters to represent n ; Vector to store the digit sum with respective elements ; Inserting digit sum with elements in the vector pair ; Making the vector pair ; Sort the vector , this will sort the pair according to the sum of letters to represent n ; Prlet the sorted vector content ; Driver Code
let letters = [ 4 , 3 , 3 , 3 , 4 , 4 , 3 , 5 , 5 , 4 ] ; function sumOfLetters ( n ) { let sum = 0 ; while ( n > 0 ) { sum += letters [ n % 10 ] ; n = Math . floor ( n / 10 ) ; } return sum ; } function sortArr ( arr , n ) { let vp = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { vp . push ( [ sumOfLetters ( arr [ i ] ) , arr [ i ] ] ) ; } vp . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ; for ( let i = 0 ; i < vp . length ; i ++ ) document . write ( vp [ i ] [ 1 ] + " " ) ; } let arr = [ 12 , 10 , 31 , 18 ] ; let n = arr . length ; sortArr ( arr , n ) ;