数组对象求交集
list1与 list2 的交集,与list1,list2的顺序无关
let list1 = [{id:1,name:'aaa'},{id:2,name:'bbb'}]
let list2 = [{id:1,name:'aaa'},{id:2,name:'bbb'},{id:3,name:'bbb'}]
let arrIds = list2.map(item => item.id); // 取唯一的标识
let result = list1.filter(item => arrIds.includes(item.id))
// result = [{id: 1, name: "aaa"},{id: 2, name: "bbb"}]
数组对象求差集
数据多的使用filter
let list1 = [{id:1,name:'aaa'},{id:2,name:'bbb'}]
let list2 = [{id:1,name:'aaa'},{id:2,name:'bbb'},{id:3,name:'bbb'}]
let result = list2.filter(e=>{
var str = JSON.stringify(e)
return list1.every(e=>JSON.stringify(e)!=str);
})
// result = [{id: 3, name: "bbb"}]
数组对象去重
对list去重,唯一标识id
noRepect(list){ //去重
let hash = {}
return list.reduce((preVal, curVal) => {
hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push(curVal)
return preVal
}, [])
}
数组对象统计个数并去重
getSelectListInfo(val){
let result = []
let arr = []
val.map(i => {
arr.push(i.name)
}) //提取需要统计的元素
// 放到map对象中进行统计
let map = arr.reduce((m, x) => m.set(x, (m.get(x) || 0) + 1), new Map())
map.forEach((value, key)=>{
result.push({
text: key,
num: value
})
}) //取值结果 [{text: '...', num: '...'}, ...]
return result
},
数组对象真正去重
let obj = {}
point = point.reduce((sum, current) => {
if (!obj[JSON.stringify(current)]) {
obj[JSON.stringify(current)] = true
sum.push(current)
}
return sum
}, [])
数组对象排序
let list = [{id:3,name:'ccc'},{id:1,name:'aaa'},{id:2,name:'bbb'}]
list.sort((a,b) => {
return a.id - b.id
}) //从小到大排序,也可以是字符串(按字母顺序排)
// list = [{id:1,name:'aaa'},{id:2,name:'bbb'},{id:3,name:'ccc'}]
匹配数组对象
for (const key in this.ruleFormData) {
this.ruleFormData[key] = data[key]
}
// this.ruleFormData 去匹配 data