- 判断数组b是否为数组a的子集:
const isSubset = b.every(item => a.includes(item));
if (isSubset) {
console.log('数组b是数组a的子集');
} else {
console.log('数组b不是数组a的子集');
}
- 判断数组a和数组b是否完全相同:
const isSame = a.length === b.length && a.every((item, index) => item === b[index]);
if (isSame) {
console.log('数组a和数组b完全相同');
} else {
console.log('数组a和数组b不完全相同');
}
- 判断数组a和数组b是否有交集:
const intersection = a.filter(item => b.includes(item));
if (intersection.length > 0) {
console.log('数组a和数组b有交集');
} else {
console.log('数组a和数组b没有交集');
}
- 判断数组a和数组b是否互不相交:
const disjoint = !a.some(item => b.includes(item));
if (disjoint) {
console.log('数组a和数组b互不相交');
} else {
console.log('数组a和数组b存在交集');
}
综合示例:
compareArr(arr1 = [], arr2 = []) {
const setA = new Set(arr1);
const setB = new Set(arr2);
const intersection = new Set([...setA].filter(x => setB.has(x))); // 交集
const union = new Set([...setA, ...setB]); // 并集
const differenceA = new Set([...setA].filter(x => !setB.has(x))); // a数组中有而b数组中没有的元素
const differenceB = new Set([...setB].filter(x => !setA.has(x))); // b数组中有而a数组中没有的元素
if (intersection.size === 0) {
return 'disjoint'; // a、b不相交
} else if (intersection.size === setA.size && intersection.size === setB.size) {
return 'equal'; // a、b相等
} else if (intersection.size === setA.size) {
return 'subset'; // a是子集
} else if (intersection.size === setB.size) {
return 'superset'; // a是父集
} else {
return 'mix';// a、b相交但不包含
}
}