Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to do Array Sort

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 47
    Comment on it

    Use the Array objects sort method:

    var fruitArray = ['strawberry','apple','orange','banana','lime'];
    alert(fruitArray.sort()); // returns apple,banana,lime,orange,strawberry


    The Array objects sort method sorts the array elements alphabetically. To make the sort easy, all data types are converted to their string equal in value before sorting:

    var numberArray = [4,13,2,31,5];
    alert(numberArray.sort()); // returns 13,2,31,4,5
    


    In this example the numbers are the array members, theyre sorted in lexicographical (dictionary) order, not numerically. To do an actual numeric sort, use a custom sort function:

    function compareNumbers(a,b) {
    return a - b;
    }
    var numArray = [13,2,31,4,5];
    alert(numArray.sort(compareNumbers)); // prints 2,4,5,13,31
    

    The second parameter value will be subtracted by the function from the first, Also if the second value is greater then the first one then the positive value will be returned else the it will return negative. If the return value is less than zero, the sort index for the second parameter is set higher than the first parameter. If the value is greater than zero, the sort index for the first parameter is set higher than the other. If the value is exactly zero, the sort index for the two is unchanged.
    If the array elements contain strings that could be converted to numbers, then the compare Numbers sort function still works, as number conversion is automatic:

    var numberArray=["34","4","5"];
    alert(numberArray.sort(compareNumbers)); // prints 4,5,34
    


    The sort method sorts the elements in an ascending order. If you want to do a reverse sort, use the sort method to sort the elements, and then use the reverse method to reverse the array member order:

    var numberArray = [4,5,1,3,2];
    numberArray.sort();
    numberArray.reverse(); // array now has 5,4,3,2,1
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: