The function should return documents including A and B and C and D for array of A, B, C, D. But it actually returns documents including (A and B) or (A and C) or (A and D).
The first loop is for first set and the second one is for others. Whenever it matches it sets the variable. Even if next word is not in the document, it's already put in the array.
There were originally three loops, but I realized this only needs two loops.