SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: need Help

  1. #1
    SitePoint Member
    Join Date
    May 2011
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    need Help

    not sure I understand the concept behind merging two arrays together. I know that I have to make a deep copy of each array before applying the function. I know that I have to create a temp value to store the information in the arrays while I insert, but not sure how to keep in numeric order. array 1 = [3, 7, 12, 15, 22, 45, 56] and array 2 = [1, 2, 5, 17, 20] What simple code could I start with to create this. Must use a for and while loop and new array must stay ordered.

  2. #2
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Location
    Dartmouth, MA, USA
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Is there any reason you can't call Array's sort() method on the new array once you've finished filling it with the contents of the two original arrays?

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by bhawk90 View Post
    Is there any reason you can't call Array's sort() method on the new array once you've finished filling it with the contents of the two original arrays?
    Because it might be some homework that he's expected to do.

    Normally you would use .concat() to merge two arrays, and the .sort() method to sort them in to numerical order.

    Code javascript:
    var arr1 = [3, 7, 12, 15, 22, 45, 56];
    var arr2 = [1, 2, 5, 17, 20];
    var arrMerged = arr1.concat(arr2).sort(function (a, b) {
        return a - b;
    });

    Which gives: [1, 2, 3, 5, 7, 12, 15, 17, 20, 22, 45, 56]
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

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