我们需要编写一个JavaScript函数,该函数接受任意数量的数组,并返回所有数组共有的元素数组。如果没有公共元素,那么我们应该返回一个空数组。
因此,让我们为该函数编写代码-
为此的代码将是-
const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];
const arr2 = [5, ,7, 2, 2, 1, 3];
const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];
const intersection = (arr1, arr2) => {
const res = [];
for(let i = 0; i < arr1.length; i++){
if(!arr2.includes(arr1[i])){
continue;
};
res.push(arr1[i]);
};
return res;
};
const intersectMany = (...arrs) => {
let res = arrs[0].slice();
for(let i = 1; i < arrs.length; i++){
res = intersection(res, arrs[i]);
};
return res;
};
console.log(intersectMany(arr1, arr2, arr3));输出结果
控制台中的输出将为-
[2, 1, 3]