Sort variables names by their values

Discussion in 'JavaScript' started by Koen, Dec 25, 2007.

  1. #1
    Hi,
    I know how to sort numbers with javascript:

    var a = 1
    var b = 2
    var c = 3
    
    document.write(Math.min(a,b,c))
    
    Code (markup):
    The Output:
    1
    Code (markup):
    I would like to have as output the variable which present the lowest value.
    So, in this case, my output should be 'a' because a has the lowest value.


    Can someone help me?
    Thx in advance and Merry Christmas;)
     
    Koen, Dec 25, 2007 IP
  2. faceless

    faceless Peon

    Messages:
    34
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Why do you need the name of the variable? Do you need the variable further down in the script?

    Seems strange to me?! :)
     
    faceless, Dec 25, 2007 IP
  3. Koen

    Koen Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Yes I need it further down.
    I am creating an algorithm (shortest path), when the value of a point is lower than the values of the other points, you have to add that point to a list so I can see which points are left, the algorithm is finished when all points are in the list.
     
    Koen, Dec 25, 2007 IP
  4. locdev

    locdev Active Member

    Messages:
    171
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    58
    #4
    try this code from w3schools
    
    <script type="text/javascript">function sortNumber(a,b)
    {
    return a - b;
    }var arr = new Array(6);
    arr[0] = "10";
    arr[1] = "5";
    arr[2] = "40";
    arr[3] = "25";
    arr[4] = "1000";
    arr[5] = "1";document.write(arr + "<br />");
    document.write(arr.sort(sortNumber));</script> 
    
    Code (markup):
     
    locdev, Dec 25, 2007 IP
  5. temp2

    temp2 Well-Known Member

    Messages:
    1,231
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    150
    Digital Goods:
    2
  6. Koen

    Koen Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    The scripts you gave me are to sort the values of the array, I needed the names of the Array.
    I just found a good script:

    <script language="javascript">
    var myArray = Array();
    myArray["A"] = 3;
    myArray["B"] = 2;
    myArray["C"] = 5;
    	
    var lowest = "";
    	
    for (key in myArray) {
    	if (lowest == "" || myArray[key] < myArray[lowest]) {
    		lowest = key;
    	}
    }
    document.write(lowest)
    </script>
    Code (markup):
    Thx anyway for your help;)
     
    Koen, Dec 26, 2007 IP