如何在JavaScript中找到两个或多个数组之间的公共元素

如果只有两个数组,那么通过使用逻辑方法,可以找到公共元素。 但是,如果有更多的数组,则很难找到公共元素。 因此,为了使该过程尽可能简单,可以使用_.intersection() 方法。 它是一个javascript库-- underscore.js 框架中函数。

_.intersection()方法将检查所有数组的每个元素,并显示公共值。如果一组数组中的至少一个数组甚至没有一个公共值,那么将不会显示任何输出。

语法

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

它接受数组并尝试找出公共值并将其显示为输出。

示例

在下面的示例中, _.intersection()方法检查所提供数组的每个值,并将公共值显示为输出。 

<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>

输出结果

1,2,3,4,5

该方法不仅接受数字或字符串作为输入,还接受void、null等假值作为输入。

示例

在以下示例中,不仅传递了数字,还传递了错误的值。 _.underscore()方法仔细检查每个包含假值的值,以显示公共值。

<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>

输出结果

1,null