Replace array elements that contains K as a digit with the nearest power of K | Function to calculate the power of base nearest to x ; Stores logX to the base K ; Function to replace array elements with nearest power of K ; Traverse the array ; Convert integer into a string ; If K is found , then replace with the nearest power of K ; Print the array ; Given array ; Given value of K ; Function call to replace array elements with nearest power of K
function nearestPow ( x , base ) { let k = Math . floor ( Math . log ( x ) / Math . log ( base ) ) ; if ( Math . abs ( Math . pow ( base , k ) - x ) < Math . abs ( Math . pow ( base , ( k + 1 ) ) - x ) ) return Math . pow ( base , k ) ; else return Math . pow ( base , ( k + 1 ) ) ; } function replaceWithNearestPowerOfK ( arr , K , n ) { for ( let i = 0 ; i < n ; i ++ ) { let strEle = arr [ i ] . toString ( ) ; for ( let c = 0 ; c < strEle . length ; c ++ ) { if ( ( strEle - ' ' ) == K ) { arr [ i ] = nearestPow ( arr [ i ] , K ) ; break ; } } } for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) } let arr = [ 432 , 953 , 232 , 333 ] ; let n = arr . length ; let K = 3 ; replaceWithNearestPowerOfK ( arr , K , n )