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..?
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.
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.
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.
$.extend(arr1,arr2)
This will copy (and overwrite duplicates) from arr2 to arr1.
Ref: http://api.jquery.com/jQuery.extend/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With