Sort a string according to the order defined by another string | Javascript program to sort a string according to the order defined by a pattern string ; Sort str according to the order defined by pattern . ; Create a count array stor count of characters in str . ; Count number of occurrences of each character in str . ; Traverse the pattern and print every characters same number of times as it appears in str . This loop takes O ( m + n ) time where m is length of pattern and n is length of str . ; Driver code
let MAX_CHAR = 26 ; function sortByPattern ( str , pat ) { let count = new Array ( MAX_CHAR ) ; for ( let i = 0 ; i < MAX_CHAR ; i ++ ) { count [ i ] = 0 ; } for ( let i = 0 ; i < str . length ; i ++ ) { count [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } let index = 0 ; for ( let i = 0 ; i < pat . length ; i ++ ) { for ( let j = 0 ; j < count [ pat [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ; j ++ ) { str [ index ++ ] = pat [ i ] ; } } } let pat = " " . split ( " " ) ; let str = " " . split ( " " ) ; sortByPattern ( str , pat ) ; document . write ( ( str ) . join ( " " ) ) ;