1.找出两个数组中的交集?
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]
let Intersection = []
for(let i = 0; i < arr1.length;i++){
let _item = arr1[i]
for(let j = 0; j < arr2.length;j++){
if(_item === arr2[j]){
Intersection.push(_item)
}
}
}
console.log(Intersection) //[4]
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]
console.log(arr1.filter(item => arr2.includes(item))) //[4]
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]
let _arr = arr1.concat(arr2).sort()
let result = []
_arr.reduce((pre,now) => {
if(pre === now){
result.push(now)
}
return now
})
console.log(result) //[4]
2.找出两个数组中的并集?
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]
let result = [...new Set(arr1.concat(arr2))]
console.log(result) //[1, 2, 3, 4, 5, 6]
let arr1 = [1,2,3,4]
let arr2 = [4,5,6]
let _arr = [...arr1,...arr2].sort()
let result = []
_arr.reduce((pre,now) => {
if(pre !== now){
result.push(now)
}
return now
})
console.log(result) //[1, 2, 3, 4, 5, 6]
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 3, 6]
let obj = {}
arr1.forEach(item => {
obj[item] = item
console.log(obj) //{ 1: 1, 2: 2, 3: 3 }
})
arr2.forEach(item => {
obj[item] = item
console.log(obj)}) // { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6 }
let result = Object.values(obj)
console.log(result) //[1, 2, 3, 4, 5, 6]
网友评论