Carlos
Carlos

Reputation: 73

Sort User Input and Print It

I have this problem that I've been working on for a few hours with no luck. I'm supposed to write JavaScript code that prompts the user to enter 3 names (one at a time). The program should sort and display the names on different lines in ascending order.

I can get the program to prompt the user to enter the names but having difficulty sorting them and displaying them correctly.

<html>
<head>
  <title>Day 3 - Example 1</title>
</head
<body>
<center>
 <script language="javascript">

   var na1,na2,na3;
   na1=prompt("Enter your first name:","");
   na2=prompt("Enter your second name:","");
   na3=prompt("Enter your third name","");  
   var na1_na2 = compare(na1, na2);
   var na1_na3 = compare(na1, na3);
   var na2_na3 = compare(na2, na3);
   var first, second, third;

    if (na1_na2 === -1) {

       if (na1_na3 === -1) {

           first = na1;


           if (na2_na3 === -1) {

               second = na2;
               third = na3;
           } else {

               second = na3;
               third = na2;
           }
       } else {

           first = na3
           second = na1;
           third = na2;
       }
   } else {

   }
   function compare(name1, name2) {
      name1 = name1.toLowerCase();
      name2 = name2.toLowerCase();

      if (name1 === name2) return 0;

      var lengthOfShorterName = Math.min(name1.length, name2.length)

      for (var i = 0; i < lengthOfShorterName; i++) {
          if (name1.charAt(i) > name2.charAt(i)) return 1;
          if (name1.charAt(i) < name2.charAt(i)) return -1;
      }

      if (name1.lenght < name2.length) return -1;
      return 1;
  }

 </script>
 </center>
</body>
</html>

Upvotes: 0

Views: 955

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65815

Just put the names into an array and use Array.sort to order them.

// Create a new, empty array
var names = [];

// Prompt for the names and put each into the array:
names.push(prompt("Enter your first name:",""));
names.push(prompt("Enter your middle name:",""));
names.push(prompt("Enter your last name:",""));

// Sort the names:
names.sort();

// Print the results:
names.forEach(function(value){
  console.log(value);
});

Upvotes: 2

Related Questions