sort method in array

Discussion in 'JavaScript and AJAX' started by neo_vi, Jan 9, 2009.

  1. neo_vi

    neo_vi Member

    Joined:
    Feb 1, 2008
    Messages:
    720
    Likes Received:
    16
    Trophy Points:
    18
    Occupation:
    Software engineer
    Location:
    Earth
    Home Page:
    http://computertipaday.blogspot.com
    In javascript, if we declare an array and sort it, it doesn't sort it as numbers, it always perform sort like strings.
    for e.g
    Code:
    var array1={1,33,4,56,7,99,9};
    array1.sort();
    document.write(array1);
    
    this wont return the correct result. how to perform a number sort.
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    48
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Code:
    var array1=[1,33,4,56,7,99,9];
    array1.sort(sortNumber);
    document.write(array1);
    function sortNumber(a,b)
    {
    	return a - b;
    }
     
  3. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    48
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Reverse sort

    Code:
    var array1=[1,33,4,56,7,99,9];
    array1.sort(sortNumber);
    document.write(array1);
    function sortNumber(a,b)
    {
    	return b - a;
    }
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice