这几种情况应用场景都很广泛,所以总结一下。
//求两个对象数组的交集
1.求交集
var arr1 = [{id:1,name:'apple'},{id:2,name:'banana'},{id:3,name:'cat'}];
var tmpArr = [];
for (var i=0,len=arr1.length;i<len;i++){
tmpArr.push(arr1[i].id)
}
var arr2 = [{id:1,name:'apple'},{id:2,name:'banana'},{id:3,name:'cat'},{id:4,name:'dog'},{id:5,name:'egg'}];
var result = arr2.filter(function(item){
return tmpArr.indexOf(item.id)!==-1 // 利用filter方法来遍历是否有相同的元素
})
//并集
var arr1 = [{id:1,name:'apple'},{id:2,name:'banana'},{id:3,name:'cat'}];
var arr2 = [{id:1,name:'apple'},{id:2,name:'banana'},{id:3,name:'cat'},{id:4,name:'dog'},{id:5,name:'egg'}];
var arr3 = arr1.concat(arr2);
var result = [];
var obj = [];
result &#