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!
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With