Sort an array in increasing order of their Multiplicative Persistence | Function to find the number of steps required to reduce a given number to a single - digit number ; Stores the required result ; Iterate until a single digit number is not obtained ; Store the number in a temporary variable ; Iterate over all digits and store their product in num ; Increment the answer by 1 ; Return the result ; Comparator function to sort the array ; Count number of steps required to reduce X and Y into single digits integer ; Return true ; Function to sort the array according to the number of steps required to reduce a given number into a single digit number ; Sort the array using the comparator function ; Print the array after sorting ; Driver Code ; Function Call
function countReduction ( num ) { let ans = 0 ; while ( num >= 10 ) { let temp = num ; num = 1 ; while ( temp > 0 ) { let digit = temp % 10 ; temp = Math . floor ( temp / 10 ) ; num *= digit ; } ans ++ ; } return ans ; } function compare ( x , y ) { let x1 = countReduction ( x ) ; let y1 = countReduction ( y ) ; if ( x1 < y1 ) return - 1 ; return 1 ; } function sortArray ( a , n ) { a . sort ( compare ) ; for ( let i = 0 ; i < n ; i ++ ) { document . write ( a [ i ] + " " ) ; } } let arr = [ 39 , 999 , 4 , 9876 ] ; let N = arr . length ; sortArray ( arr , N ) ;