Reputation: 6684
a = [1, 2, 3, 4, 5]
b = [1, 3, 6, 4, 5, 9]
c = [5, 4, 7, 9]
d = [1, 7, 5, 6, 9, 4]
e = [4, 3, 5, 7, 1]
f = [...]
.
.
(n = [n,n,n])
For 1 out of many cases, we have 5 variables from a to e and we would like to get the intersection element out of these 5 arrays, without having to write nested for..loop for each case.
Please suggest the ideal solution to this problem.
Upvotes: 1
Views: 1794
Reputation: 63524
Here's the non-Mr.Fancy-Pants version :)
function findIntersection() {
// turns the list of arguments into an array
var args = Array.prototype.slice.call(arguments);
// concatenate all the arrays
var all = args.reduce(function (a, b) { return a.concat(b); });
// use the temporary object to store the number of times a
// number appears
for (var i = 0, obj = {}, l = all.length; i < l; i++) {
var key = all[i];
if (!obj[key]) obj[key] = 0;
obj[key]++;
}
// return those numbers that have a value matching the number
// of arguments passed into the function
return Object.keys(obj).filter(function (el) {
return obj[el] === args.length;
}).map(Number);
}
findIntersection(a,b,c,d,e); // [ "4", "5" ]
Upvotes: 1
Reputation: 239443
First find the common elements between first and the second arrays and then find the common elements between the previous set of common elements and the third array and so on.
var listOfArrays = [a, b, c, d, e, ...];
var commons = listOfArrays.slice(1).reduce(function(result, currentArray) {
return currentArray.filter(function(currentItem) {
return result.indexOf(currentItem) !== -1;
});
}, listOfArrays[0]);
Here,
currentArray.filter(function(currentItem) {...});
is the function responsible for finding the common elements between two arrays, result
and currentArray
.
We use Array.prototype.reduce
where the value returned by the function passed to it will be fed back to the same function, in the next iteration. So, we keep on feeding the common elements from the previous iteration to the next iteration.
Upvotes: 5