How to find the common elements between two or more arrays in JavaScript?


If there are only two arrays then by using logical methods, it is possible to find the common elements. But if there are more arrays then it is difficult to find the common elements. So to make the process as easy as possible, the _.intersection() method comes into the picture. It is a function in underscore.js framework, a library of javascript.

_.intersection() method will checks each and every element of all the arrays and displays the common values. If atleast one array in a group of arrays doesn't have even one common value then no output will be displayed.

syntax

_.intersection( array1, array2, .... );

It accepts arrays and tries to figure out the common values and displays them as the output.

Example

In the following example, the _.intersection() method scrutinized each and every value of the provided arrays and displayed the common values as output. 

Live Demo

<html>
<body>
<script 
   src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
   document.write(_.intersection([1, 2, 3, 4, 5],
                                 [1, 2, 3, 4, 5, 6],
                                 [1, 2, 3, 4, 5, 6, 7, 8,]));
</script>
</body>
</html>

Output

1,2,3,4,5

This method not only accepts numbers or strings as input but also accepts false values such as void, null, etc as input.

Example

In the following example, not only numbers but also false values were passed. The _.underscore() method scrutinized each and every value including false values displayed the common values.

Live Demo

<html>
<body>
<script 
   src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
   document.write(_.intersection([1, 2, 3, "null", "undefined"],
                                 [1, 2, 3, "null", "undefined", "void"],
                                 [1, "null","void"]));
</script>
</body>
</html>

Output

1,null
raja
Published on 10-Jul-2019 17:08:54
Advertisements