Sort array after converting elements to their squares | Function to sort an square array ; First convert each array elements into its square ; Sort an array using " inbuild ▁ sort ▁ function " in Arrays class . ; Driver Code
function sortSquares ( arr ) { let n = arr . length ; for ( let i = 0 ; i < n ; i ++ ) arr [ i ] = arr [ i ] * arr [ i ] ; arr . sort ( ) ; } let arr = [ - 6 , - 3 , - 1 , 2 , 4 , 5 ] ; let n = arr . length ; document . write ( " " + " " ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; sortSquares ( arr ) ; document . write ( " " + " " ) ; document . write ( " " + " " ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ;