Merge JavaScript arrays 

Joined:
02/21/2009
Posts:
172

June 17, 2014 16:27:29    Last update: June 17, 2014 16:27:29
  1. With built-in Array.concat:
    // initialize a1
    a1 = [1, 2, 3]
    
    // initialize a2
    a2 = [4, 5]
    
    // merge a2 into a1, returns [1, 2, 3, 4, 5], but a1 and a2 remain unchanged
    a1.concat(a2)
    
    // a1 and a2 are not changed
    a1 == [1, 2, 3]
    a2 == [4, 5]
    


  2. With jQuery merge:
    // initialize a1
    a1 = [1, 2, 3]
    
    // initialize a2
    a2 = [4, 5]
    
    // merge a2 into a1
    jQuery.merge(a1, a2) // returns [1, 2, 3, 4, 5], a1 is changed to the merge result
    
    a1 == [1, 2, 3, 4, 5]
    

Share |
| Comment  | Tags