javascript - How can I find the common elements in a list of arrays? -


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, have 5 variables a e , intersection element out of these 5 arrays, without having write nested for..loop each case.

please suggest ideal solution problem.

first find common elements between first , second arrays , find common elements between previous set of common elements , third array , 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 function responsible finding common elements between 2 arrays, result , currentarray.

we use array.prototype.reduce value returned function passed fed same function, in next iteration. so, keep on feeding common elements previous iteration next iteration.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -