traversing string from the end .
for ( let i = str . length - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == ' ' ) { let s = [ ] ; while ( arr [ arr . length - 1 ] != ' ' ) { s . push ( arr [ arr . length - 1 ] ) ; arr . pop ( ) ; } arr . pop ( ) ;