1.映射,避开双重循环
let arr1 = [
{ id: 3, city: '上海' },
{ id: 1, city: '北京' },
{ id: 4, city: '成都' },
]
let arr2 = [
{ id: 1, city: '北京' },
{ id: 2, city: '天津' },
{ id: 3, city: '上海' },
{ id: 5, city: '云南' }
]
function intersection (arr1, arr2) {
let obj = {}
arr1.forEach(item => {
obj[item.id] = true
})
let newArray = arr2.filter(item => {
return obj[item.id]
})
return newArray
}
let arrInerst = intersection(arr1, arr2)
console.log(arrInerst)
2.include()方法
include()的原理是遍历,不建议在遍历中再使用include(), 推荐使用映射
let arr1 = [
{ id: 3, city: '上海' },
{ id: 1, city: '北京' },
{ id: 4, city: '成都' },
]
let arr2 = [
{ id: 1, city: '北京' },
{ id: 2, city: '天津' },
{ id: 3, city: '上海' },
{ id: 5, city: '云南' }
]
function intersection (arr1, arr2) {
let arr = arr1.map(item => {
return item.id
})
let newArray = arr2.filter(item => {
return arr.includes(item.id)
})
return newArray
}
let arrInerst = intersection(arr1, arr2)
console.log(arrInerst)
}
双重循环
let arr1 = [
{ id: 3, city: '上海' },
{ id: 1, city: '北京' },
{ id: 4, city: '成都' },
]
let arr2 = [
{ id: 1, city: '北京' },
{ id: 2, city: '天津' },
{ id: 3, city: '上海' },
{ id: 5, city: '云南' }
]
function intersection (arr1, arr2) {
let newArray = []
arr1.forEach(item => {
for (let i=0; i<arr2.length; i++) {
if (arr2[i].id === item.id) {
newArray.push(arr2[i])
break
}
}
})
return newArray
}
let arrInerst = intersection(arr1, arr2)
console.log(arrInerst)
以上结果都为: