Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Oct 2006
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Newbie who needs help with array function

    How could I implement two sort functions w/o using the "sort" built-in-method: 1) the first will return a sorted array 2) the second will sort the array passed into it directly - the first function called f1 can be called by:

    var a = [2, 4, 3, 1];
    var b = f1(a, "d");

    After execution, a shouldn't be changed and b should become an array containing [4,3,2,1]

    Second function called f2 and be called using this code:

    var a = [2, 4, 3, 1];
    f2(a, "d");

    After execution, a should contain [4, 3, 2, 1]

    If anyone can help I would greatly appreciate it!!!

  • #2
    Regular Coder
    Join Date
    May 2005
    Posts
    142
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Just use the built in sort method. it will be faster than anything you can write in javascript....

    If you don't want the array to be changed, coppy it.

    If you need a numeric sort, define your own sort function...

    Code:
    var myArr = [4, 1, 3, 2];
    
    //Copy myArr so that it doesn't change.
    var arr = new Array();
    arr.concat(myArr);
    
    arr.sort(function(a,b){return a-b}); //ascending numeric sort
    arr.sort(function(a,b){return b-a}); //descending numeric sort
    The only reason you need to write your own sort routine without using the built in sort is if you're doing this for a class... If you're doing this for a class, then post the code you're having problems with and we'll help. We will not do the work for you.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •