我有以下函数,用于返回某些字符串数组之间的元素的交集。
最初它只打算处理2个数组,但是我开始需要它处理2个以上的数组,因此我添加了条件return
以使其递归。
我如何使其具有足够的灵活性,使其能够处理任意数量的数组(当然等于或大于2)。
我虽然使用...rest
参数,但是我还不知道该怎么做。
function intersection(list1, list2, list3, list4) {
const result = [];
for (let i = 0; i < list1.length; i++) {
let item1 = list1[i];
let found = false;
for (var j = 0; j < list2.length && !found; j++) {
found = item1 === list2[j];
}
if (found === true) {
result.push(item1);
}
}
if (list3 && list4) {
return intersection(result,list3,list4);
}
if (list3) {
return intersection(result,list3);
}
return result;
}
SNIPPET
function intersection(list1, list2, list3, list4) {
const result = [];
for (let i = 0; i < list1.length; i++) {
let item1 = list1[i];
let found = false;
for (var j = 0; j < list2.length && !found; j++) {
found = item1 === list2[j];
}
if (found === true) {
result.push(item1);
}
}
if (list3 && list4) {
return intersection(result,list3,list4);
}
if (list3) {
return intersection(result,list3);
}
return result;
}
const x1 = ['a','b','c','d','e'];
const x2 = ['a','b','c','d'];
const x3 = ['a','b','c'];
const x4 = ['a','b'];
console.log('Intersection(x1,x2,x3,x4): ' + JSON.stringify(intersection(x1,x2,x3,x4)));
console.log('Intersection(x1,x2,x3): ' + JSON.stringify(intersection(x1,x2,x3)));
console.log('Intersection(x1,x2): ' + JSON.stringify(intersection(x1,x2)));
无需递归,您可以使用rest参数...
并获取交集aSet
并对其进行过滤。
function intersection(...arrays) {
return arrays.reduce((a, b) => a.filter(Set.prototype.has, new Set(b)));
}
console.log(intersection(['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c'], ['a', 'b']));
console.log(intersection(['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c']));
console.log(intersection(['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd']));
带有递归的版本
function intersection(a, b = [], ...arrays) {
var i = a.filter(Set.prototype.has, new Set(b));
return arrays.length
? intersection(i, ...arrays)
: i;
}
console.log(intersection(['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c'], ['a', 'b']));
console.log(intersection(['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c']));
console.log(intersection(['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd']));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句