?
Solved

JavaScript sort function always sorts by ascending order, NOT descending

Posted on 2005-04-04
5
Medium Priority
?
430 Views
Last Modified: 2008-03-17
Hello.

I am trying to allow ascending or descending sorting using the sort function, but my list ALWAYS comes up in ascending order.  I've thrown together a sample program (below) exemplifying my problem.  What am I doing wrong? (I'm a newbie and just starting to learn JavaScript.)

It looks as if my SortIt function always returns the wrong value.

Thanks in advance.

-Brian


<html>
                 <head>
            <script language = "JavaScript">
            <!--
            var InputText = prompt ('Enter a text string below:', ' ');
            var Word = InputText.split (" ")
            var OrderType = prompt ('Enter order type ("ascending" or "descending"):');

            function SortIt (a, b){

                  RetValue = 0

                  if (a < b)
                      RetValue = -1
                  else
                      if (a > b)
                             RetValue = 1

                  return RetValue;
    }

            //-->
            </script>
      </head>

      <body>
            <script language = "JavaScript">
            <!--
            document.writeln ("Original:<br>");
            for (i = 0; i < Word.length; i++)
                   document.writeln (Word[i] + '<br>');


            Word.sort (SortIt);
            document.writeln ("<br>Sorted:<br>");
            for (i = 0; i < Word.length; i++)
             document.writeln (Word[i] + '<br>');
            //-->
            </script>
      </body>
</html>
0
Comment
Question by:bek
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 32

Accepted Solution

by:
Batalf earned 200 total points
ID: 13701317
OrderType isn't used in the function, You have to implement it into the SortIt function.

Here's an example.

<html>
                 <head>
          <script language = "JavaScript">
          <!--
          var InputText = prompt ('Enter a text string below:', ' ');
          var Word = InputText.split (" ")
          var OrderType = prompt ('Enter order type ("ascending" or "descending"):');

          function SortIt (a, b){

               RetValue = 0
               a=a+"";
               a = a.toLowerCase();
               b=b+"";
               b = b.toLowerCase();
               if (a < b)
                   RetValue = -1
               else
                   if (a > b)
                          RetValue = 1
               if(OrderType=='descending')RetValue = RetValue*-1;
               return RetValue;
         }

          //-->
          </script>
     </head>

     <body>
          <script language = "JavaScript">
          <!--
          document.writeln ("Original:<br>");
          for (i = 0; i < Word.length; i++)
                document.writeln (Word[i] + '<br>');


          Word.sort (SortIt);
          document.writeln ("<br>Sorted:<br>");
          for (i = 0; i < Word.length; i++)
           document.writeln (Word[i] + '<br>');
          //-->
          </script>
     </body>
</html>
0
 

Author Comment

by:bek
ID: 13706744
Hey, that works.  Thanks very much.

Can you explain a couple of things to me... Why are you doing this:  a=a+"" ?

Also, instead of this:

     if(OrderType=='descending')RetValue = RetValue*-1;

why didn't you say this:

     if(OrderType=='descending')RetValue = -1;

Aren't they the same thing?
0
 
LVL 32

Expert Comment

by:Batalf
ID: 13706810
a=a+"b":

a=a+"" is there to convert it to a string. If it's considered to be a number by Javascript, the toLowerCase() function will fail.

if(OrderType=='descending')RetValue = -1; :
the sortIt() compares two items from your array, and set RetValue to -1 if "a" is less than "b" and 1 if "a" is higher than "b". That's why use this line:

if(OrderType=='descending')RetValue = RetValue*-1;

to return the oposite result from the function if you're sorting the items in descending order.

If you use

if(OrderType=='descending')RetValue = -1;

and a is less than b, it won't return the value in oposite order, since RetValue allready is -1 from the test above.

Example: The two words "Is" and "This" is sent to the function

a = "is",
b = "This"

This part of your function:

if (a < b)
                   RetValue = -1
               else
                   if (a > b)
                          RetValue = 1

set RetValue to -1 since "is" is smaller than "This". If you now uses the the line

if(OrderType=='descending')RetValue = -1;

RetValue will still be -1 and not the oposite which is 1. That's why I used

if(OrderType=='descending')RetValue = RetValue*-1;

Hope it makes sense. It's not so easy to explain:-)

Batalf
0
 

Author Comment

by:bek
ID: 13706992
That is great, Batalf.  Thanks so much!
0
 
LVL 32

Expert Comment

by:Batalf
ID: 13707012
Glad I could help! Thanks for the points

Batalf
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question