js求对象数组的交集并集差集去重
js求对象数组的交集/并集/差集/去重
1. 求交集
var arr1 = [{ name: 'name1', id: 1 }, { name: 'name2', id: 2 }, { name: 'name3', id: 3 }];
var arr1Id = [1, 2, 3]
var arr2 = [{ name: 'name1', id: 1 }, { name: 'name2', id: 2 }, { name: 'name3', id: 3 }, { name: 'name4', id: 4 }, { name: 'name5', id: 5 }]; var result = arr2.filter(function (v) {
return arr1Id.indexOf(v.id) !== -1 // 利⽤filter⽅法来遍历是否有相同的元素
})
console.log(result);
1. 求并集
let arr1 = [{name:'name1',id:1},{name:'name2',id:2},{name:'name3',id:3}];
let arr2 = [{name:'name1',id:1},{name:'name4',id:4},{name:'name5',id:5}];
let arr3 = at(arr2);
let result = [];
var obj = [];
result = duce(function(prev, cur, index, arr) {
console.log(prev, cur);
obj[cur.id] ? '' : obj[cur.id] = true && prev.push(cur);
return prev;
}, []);
console.log(result);
1. 求差集
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 = at(arr2);
let result = arr3.filter(function(v){
return arr1Id.indexOf(v.id)===-1 || (arr2Id.indexOf(v.id)===-1)
})
console.log(result);
1. 去重
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 = duce(function(prev, cur, index, arr) {
console.log(prev, cur);
obj[cur.id] ? '' : obj[cur.id] = true && prev.push(cur);
return prev;
}, []);
实际组件中应⽤去重
⽅法1:
let includeThis = false
let vm = this
if(vm.informedPersonList.length>0){
vm.informedPersonList.forEach(el =>{
if(el.id == vm.selectedTrueItem.id){
includeThis = true
}
})
}
if(includeThis===false){
vm.informedPersonList.push(vm.selectedTrueItem)
}else{
Message({message: '请勿重复添加',type: 'warning'})
}
⽅法2:
(必须先let informedPersonL = vm.informedPersonList,不能直接使⽤vm.informedPersonList,否则浏览器控制台会报错)
filter过滤对象数组vm.informedPersonList.push(this.selectedTrueItem)
let obj = {};
let informedPersonL = vm.informedPersonList
informedPersonL = duce((cur,next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
vm.selectedTrueItem = {}
vm.$emit("backInformedPList",informedPersonL);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论