1
let observable = Observable.from([[ 'a' , 'b' , 'c' ],[ 'b', 'c' ],[ 'd' , 'c' , 'b' ]]);

I need to transform this observable so that it emits the intersection of those 3 arrays

What is the simplest way?

observable
    .intersection() // Expected operator
    .subscribe( letter =>  console.log( letter ));

out put should be

b
c 

or

c
b
Mark Timothy
  • 1,784
  • 5
  • 19
  • 30

1 Answers1

2

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.

Daniel B
  • 8,770
  • 5
  • 43
  • 76