Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate two array objects using jquery without adding duplicates

Tags:

jquery

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..?

like image 857
user882196 Avatar asked Aug 17 '11 21:08

user882196


People also ask

How do I merge two arrays of objects without duplicates?

concat() can be used to merge multiple arrays together. But, it does not remove duplicates. filter() is used to identify if an item is present in the “merged_array” or not. Just like the traditional for loop, filter uses the indexOf() method to judge the occurrence of an item in the merged_array.

How do I merge two arrays in TypeScript without duplicates?

Using ES5 we can merge the two input arrays without removing the duplicates with . concat() and then loop again through the result array and remove duplicates using indexOf.

How do you remove duplicates in array of objects in JS?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.


1 Answers

$.extend(arr1,arr2)

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

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

like image 55
PhD Avatar answered Sep 28 '22 06:09

PhD