How to correctly return the word?

0

function ordenar(string){
  var abc = 'abcdefghijklmnopqrstuvwxyz',
      to = abc.split(''),
      str = string.split('');
      
      for(let i=0;i<to.length;i++){
         for(let j=0;j<str.length;j++){
           if(str[j] == to[i]) console.log(to[i]);
         }
      }
}

ordenar('hola');

As you can see in the console it shows ahlo , but I want it to show how it was originally hola , what is the error or how should it be done?

    
asked by Eduardo Sebastian 24.09.2017 в 19:56
source

1 answer

1

The flow of your code should be around because the first letter of the variable abc is a , which means that the second loop, search in each letter of the variable string the word a which is number 4 and will print it first.

Putting it always, if you invest the for, it will work perfect:

function ordenar(string){
  var abc = 'abcdefghijklmnopqrstuvwxyz',
      to = abc.split(''),
      str = string.split('');
      
    for(let j=0; j<str.length; j++)
    {
      for(let i=0; i< to.length; i++)
      { 
           if(str[j] == to[i]) 
           {
              console.log(to[i]);
              break;// detenemos el for
            }
         }
      }
}

ordenar('hola');
    
answered by 24.09.2017 / 20:10
source