Нет необходимости в рекурсии, вы можете взять остальные параметры ...
и получить пересечение a Set
и отфильтровать его.
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']));