Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding intersection in multiple arrays

I am trying to find the intersecting values in multiple arrays, that are within an object as follows:

object = {
  filterA: ["1","2","3","4"],
  filterB: ["2","5","6","7"],
  filterN: ["2","4","7"]
}

The object can hold multiple arrays and the name of the keys can vary. In the described object I need only "2" to be returned.

I have tried to build on this answer: Multiple array intersection in javascript but I could not figure it out, as it uses static variables (a,b,c) for the example. If there is a way to do that with lodash, it will be appreciated, but vanilla javascript in ES 5 will do as well!

like image 461
Presian Nedyalkov Avatar asked Mar 24 '19 10:03

Presian Nedyalkov


People also ask

How do you find the intersection of multiple arrays?

We are required to write a JavaScript function that takes in any arbitrary number of arrays and returns an array of elements that are common to all arrays. If there are no common elements, then we should return an empty array.

How do you find the union and intersection of multiple arrays in Java?

To find the union, add the first array's elements to the set union. Now, add all the second array elements if they are not present in the set union. To find the intersection, find the common elements and add them to the set. Here is the source code of the Java Program to Find the Union and Intersection of 2 Arrays.


1 Answers

You could get the values and take a Set and filter with Set#has.

var object = { filterA: ["1", "2", "3", "4"], filterB: ["2", "5", "6", "7"], filterN: ["2", "4", "7"] },
    result = Object
        .values(object)
        .reduce((a, b) => b.filter(Set.prototype.has, new Set(a)));

console.log(result);
like image 161
Nina Scholz Avatar answered Sep 18 '22 10:09

Nina Scholz