在JavaScript中查找任意数量的数组之间的公共项
假设我们有一个数字数组的对象,如下所示:
const obj = {
a: [ 15, 23, 36, 49, 104, 211 ],
b: [ 9, 12, 23 ],
c: [ 11, 17, 18, 23, 38 ],
d: [ 13, 21, 23, 27, 40, 85]
};对象中元素的数量不是固定的,并且可以具有任意数量的元素。
我们需要编写一个JavaScript函数,该函数接受一个这样的对象并返回每个成员数组共有的元素数组。
因此,对于上述目的,输出应为-
const output = [23];
示例
为此的代码将是-
const obj = {
a: [ 15, 23, 36, 49, 104, 211 ],
b: [ 9, 12, 23 ],
c: [ 11, 17, 18, 23, 38 ],
d: [ 13, 21, 23, 27, 40, 85]
};
const commonBetweenTwo = (arr1, arr2) => {
const res = [];
for(let i = 0; i < arr1.length; i++){
if(arr2.includes(arr1[i])){
res.push(arr1[i]);
};
};
return res;
};
const commonBetweenMany = (obj = {}) => {
const keys = Object.keys(obj);
let res = obj[keys[0]];
for(let i = 1; i < keys.length - 1; i++){
res = commonBetweenTwo(res, obj[keys[i]]);
if(!res.length){
return [];
};
};
return res;
};
console.log(commonBetweenMany(obj));输出结果
控制台中的输出将是-
[23]