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

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -