1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

sort method in array

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

  1. neo_vi

    neo_vi New Member

    Joined:
    Feb 1, 2008
    Messages:
    722
    Likes Received:
    15
    Trophy Points:
    0
    Occupation:
    Software engineer
    Location:
    Earth
    Home Page:
    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,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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