Skip to content
Advertisement

How to insert a function inside another function and alphabetize a phrase?

I take the opportunity to ask two things, the first I want to alphabetically order a phrase that the user previously writes but for some reason it does not finish printing the result, the second is to read the phrase and indicate if there is any repeated word and how many times it is repeated and show it On the screen of course, I wanted to do it with a function but I don’t know how to put one function inside another:

Here I attach code:

 var Miventana;
function AbrirVen() {
    //ventana secundaria
   /* pondra la ventana en el centro de la pantalla; sin importar la resolución que esté utilizando el equipo cliente.
Las variables A y H darán el tamaño a la ventana.*/
    var Ancho = screen.width;
    var Alto = screen.height;
    var A = Ancho*50/100;
    var H = Alto*50/100;
    var difA = Ancho - A;
    var difH = Alto - H;
    var tope = difH/2;
    var lado = difA/2;
    var Opciones="status=no, menubar=no, directories=no, location=no, toolbar=no, scrollbars=yes, resizable=no, width="+A+", height="+H+", top="+tope+", left="+lado+"";
    Miventana = open("página que vas a abrir","_blank",Opciones);

    var frase = document.getElementById("frase").value;
    var palabras = frase.split(" ");
    var primerapalabra = palabras[0];
    var ultimapalabra = palabras[palabras.length-1];
    var ordenLongitud = frase.slice();

        
    Miventana.document.write(`Primera palabra: ${primerapalabra}`,"<br>");
    Miventana.document.write(`Última palabra: ${ultimapalabra}`);
    var numNom = frase.length;
    Miventana.document.write("</br> Tu frase tiene " + numNom + " palabras </br>");

    frase.sort(function (a, b) {
        return a.toLowerCase().localeCompare(b.toLowerCase());
    });
    
    ordenLongitud.sort(function(a, b) {
        return a.length - b.length
    });
    
    
    Miventana.document.getElementById("letras").innerHTML = 'Alfabetico: ' + frase + '<br>Longitud: ' + ordenLongitud;


    function checkString(text,index){
        if((text.length - index)==0 ){ //stop condition
            return false; 
        }else{
            return checkString(text,index + 1) 
            || text.substr(0, index).indexOf(text[index])!=-1;
        }
    }
    
    for(var frase in texts){
        var text = texts[frase].split("");
        Miventana.document.write(text + " -> " + text.some(function(v,i,a){return a.lastIndexOf(v)!=i;}) +"<br/>");
        
    }

}

Advertisement

Answer

I want to alphabetically order a phrase that the user previously writes but for some reason it does not finish printing the result

You’re sorting the wrong variable. You should sort the palabras variable, which is an array containing the splitted words rather than frase, which is the string.

var Miventana;
function AbrirVen() {
    // [...]
    
    var frase = document.getElementById("frase").value;
    var palabras = frase.split(" ");
    var primerapalabra = palabras[0];
    var ultimapalabra = palabras[palabras.length-1];
    var ordenLongitud = frase.slice();

        
    Miventana.document.write(`Primera palabra: ${primerapalabra}`,"<br>");
    Miventana.document.write(`Última palabra: ${ultimapalabra}`);
    
    
    var numNom = frase.length; // <<< this should be palabras.length (not `frase`)
    Miventana.document.write("</br> Tu frase tiene " + numNom + " palabras </br>");

    frase.sort(function (a, b) { // <<< again you should sort palabras
        return a.toLowerCase().localeCompare(b.toLowerCase());
    });
    
    
    // [...]

}

the second is to read the phrase and indicate if there is any repeated word and how many times it is repeated and show it

You could do that by using an object which holds the counts for each word (I took that approach from How to count duplicate value in an array in javascript):

var counts = {};
palabras.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });

for (k in counts) {
  if (counts[k] > 1) {
    // Show the output however you like
    console.log(`Word '${k}' appears ${counts[k]} times`)
  }
}

Finally:

I wanted to do it with a function but I don’t know how to put one function inside another

There’s no problem at all with defining a function inside another function. We could take the counting lines above, abstract them into a function and just call it from AbrirVen():

var Miventana;
function AbrirVen() {
    // [...]
    
    var frase = document.getElementById("frase").value;
    var palabras = frase.split(" ");
    
    // [...]

    function displayCounts(words_to_be_counted) {
      var counts = {};
      words_to_be_counted.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });

      for (k in counts) {
        if (counts[k] > 1) {
            // Show the output however you like
            console.log(`Word '${k}' appears ${counts[k]} times`)
          }
        }
    }

    displayCounts(palabras)

    // [...]

}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement