-
-
Notifications
You must be signed in to change notification settings - Fork 237
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
数组交集,并集,差集 #82
Comments
const arr1 = [1, 2, 3, 4]
const arr2 = [1, 3, 5, 6, 7]
function Union () {
const args = [].slice.call(arguments)
const arrs = args.reduce((total,current) => {
return total.concat(current)
},[])
return [...new Set(arrs)]
}
console.log('------')
// 返回传入所有数组的并集
console.log(Union(arr1, arr2))
function intersections () {
let res
const args = [].slice.call(arguments).map(e => new Set(e))
args.slice(1).forEach(e => {
res = [...new Set([...args[0]].filter(x => e.has(x)))]
})
return res
}
console.log('------')
// 返回传入所有数组的交集
console.log(intersections(arr1, arr2, [3]))
function subtraction () {
const result = []
let res = []
const args = [].slice.call(arguments).map(e => new Set(e))
args.forEach((e, ei) => {
res = []
args.forEach((x, xi) => {
if (ei !== xi) {
res.push([...new Set([...e].filter(y => !x.has(y)))])
}
})
result.push(res)
})
return result
}
console.log('------')
// 返回传入的所有数组相对于其他数组的差集
console.log(subtraction(arr1, arr2, [9, 10, 11])) |
const arr1 = [1, 3, 5];
const arr2 = [2, 4, 5, 6];
// 1. 并集
const arr3 = [...new Set(arr1.concat(arr2))];
// 2. 交集
const set = new Set(arr1);
const res = [];
for (let i = 0; i < arr2.length; i++) {
if (set.has(arr2[i]) && res.indexOf(arr2[i]) === -1) {
res.push(arr2[i]);
}
}
console.log(res);
// 3. 差集 这里求的是除了交集之外的
const res2 = [...new Set(arr1.concat(arr2))];
for(let i = 0; i < res2.length; i++){
if(res.indexOf(res2[i])!== -1) res2.splice(i, 1);
}
console.log(res2); |
// 1. 并集
const res1 = [...new Set(arr1.concat(arr2))];
console.log(res1)
// 2. 交集
const set = new Set(arr1);
const res2 = [];
for (let i = 0; i < arr2.length; i++) {
if (set.has(arr2[i]) && !res2.includes(arr2[i])) {
res2.push(arr2[i]);
}
}
console.log(res2);
// 3. 差集 这里求的是除了交集之外的
const res3 = res1.filter(item => !res2.includes(item))
console.log(res3); |
let arr1 = [1,2,3] // 并集 解构+set+解构 // 交集 // 差集 arr1-arr2 |
let arr1 = [1, 2, 3, 4];
let arr2 = [3, 4, 5, 6];
// 并集
let union = [...new Set([...arr1,...arr2])];
console.log(union); // 输出:[1 ,2 ,3 ,4 ,5 ,6]
//交集
let intersection = arr1.filter(x => new Set(arr2).has(x));
console.log(intersection); // 输出:[3 ,4]
// 差集 (arr1 相对于 arr2 的差集)
let difference = arr1.filter(x => !new Set(arr2).has(x));
console.log(difference); // 输出:[1 ,2] |
const setA = new Set([1, 2, 3]); // 并集 // 交集 // 差集 |
No description provided.
The text was updated successfully, but these errors were encountered: