You can combine the use of an intersection algorithm such as this one with the .reduce
-operator.
The algorithm (credit to atk)
function intersection_destructive(a, b) {
a.sort(); <--- ADDED
b.sort(); <--- ADDED
var result = [];
while (a.length > 0 && b.length > 0) {
if (a[0] < b[0]) {
a.shift();
} else if (a[0] > b[0]) {
b.shift();
} else /* they're equal */ {
result.push(a.shift());
b.shift();
}
}
return result;
}
and how to use it with .reduce
source
.reduce((a, b) => intersection_destructive(a, b))
.subscribe((res) => {
console.log(res);
});
An important note here is that this only works with sorted arrays, but it can be modified to fit all purposes. You would also have to modify it to work with object equality checks, but I guess this gives you an idea of how it can be done.
Working jsFiddle here.