这几种情况应用场景都很广泛,所以总结一下。
//求两个对象数组的交集
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
//并集
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 = arr3.reduce(function(prev, cur, index, arr){
console.log(prev, cur);
obj[cur.id] ? '' : obj[cur.id] = true && prev.push(cur);
return prev;
}, []);
//差集
let arr1 = [{name:'name1',id:1},{name:'name2',id:2},{name:'name3',id:3}];
let arr1Id = [1,2,3];
let arr2 = [{name:'name1',id:1},{name:'name4',id:4},{name:'name5',id:5}];
let arr2Id = [1,4,5];
let arr3 = arr1.concat(arr2);
let result = arr3.filter(function(v){
return arr1Id.indexOf(v.id)===-1 || (arr2Id.indexOf(v.id)===-1)
})
console.log(result);
//去重
let arr = [{name:'name1',id:1},{name:'name2',id:2},{name:'name3',id:3},{name:'name1',id:1},{name:'name4',id:4},{name:'name5',id:5}];
var obj = [];
let result = arr.reduce(function(prev, cur, index, arr) {
console.log(prev, cur);
obj[cur.id] ? '' : obj[cur.id] = true && prev.push(cur);
return prev;
}, []);