Reducing list intersections

You can intersect list values using the reduce() method. Let's create a function that will intersect the list values given to it:

const intersect = (...lists) => {
const [head] = lists;
const tail = Seq(lists.slice(1));

return head.reduce((result, value) =>
tail
.map(list => list.includes(value))
.includes(false) ?
result : result.add(value),
Set()
);
};

The intersect() function accepts an arbitrary number of lists, using the rest parameter syntax (...). The first step is to get the head and tail of these lists. The head constant represents the first list while the tail constant represents the remaining lists.

We'll use head as the list to iterate over using reduce(). Within reduce(), we map tail to see if any of these lists contain the current value using includes(). Now we have a list of Boolean values. If any of them are false, this means that the value isn't in every list that was passed to intersect(), and we don't include it in the reduction.

As you can see, we're using Set as the reduced intersection to prevent duplicate values. Let's see what the results look like:

const myList1 = List.of(1, 2, 3, 2);
const myList2 = List.of(2, 3, 4);
const myList3 = List.of(2, 3, 5);
const myIntersection = intersect(
myList1,
myList2,
myList3
);

console.log('myList1', myList1.toJS());
// -> myList1 [ 1, 2, 3, 2 ]
console.log('myList2', myList2.toJS());
// -> myList2 [ 2, 3, 4 ]
console.log('myList3', myList3.toJS());
// -> myList3 [ 2, 3, 5 ]
console.log('myIntersection', myIntersection.toJS());
// -> myIntersection [ 2, 3 ]

With our intersect() function, we can still find the intersection between lists that have duplicate values. One downside to this approach is that it can't be done lazily because we're using reduce() to build a set. Another downside is that the code in our reduce() iteratee function isn't so straightforward.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.185.147