user882196
user882196

Reputation: 1721

How to concatenate two array objects using jquery without adding duplicates

I have two array objects :

 var arr1 =[{product_id: 2, name: 'stack'}, {product_id: 3, name: 'overflow'}];

 var  arr2 = [{product_id: 2, name: 'popo'},{product_id: 6, name: 'foo'}];

I do jquery like follows:

$.each(arr1 , function(){ 
      var productId = this.product_id;
       $.each(arr2 , function(productId){
        if(this.product_id != productId){
           arr2.push(this);
        }
       }); 
   });

at the end

arr2 must look like

     var  arr2 = [{product_id: 2, name: 'stack'}, {product_id: 3, name: 'overflow'},
             {product_id: 6, name: 'foo'}]

am i doing correct jquery coding..?

Upvotes: 6

Views: 16156

Answers (2)

Justice Erolin
Justice Erolin

Reputation: 2879

$.extend(true, arr1, arr2);

Extend joins two objects/arrays into the first object.

Upvotes: 8

PhD
PhD

Reputation: 11334

$.extend(arr1,arr2)

This will copy (and overwrite duplicates) from arr2 to arr1.

Ref: http://api.jquery.com/jQuery.extend/

Upvotes: 8

Related Questions