A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

                                            关于JS对象数组的交集、并集、差集

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.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方法来遍历是否有相同的元素
})
2.求并集
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;
}, []);
3.求差值
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);

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马