JavaScript中的多数组交集 [英] Multiple array intersection in javascript
问题描述
如何使用javascript(w/wth JQuery)来查找在数组之间相交的值?
How to write in javascript(w/wth JQuery) to find values that intersect between arrays?
应该像
var a = [1,2,3]
var b = [2,4,5]
var c = [2,3,6]
,并且交集函数应返回值为{2}的数组.如果可能的话,它可能适用于任意数量的数组.
and the intersect function should returns array with value {2}. If possible it could applicable for any number of arrays.
谢谢
推荐答案
有很多方法可以实现这一目标.
There are many ways to achieve this.
由于您使用的是jQuery,因此我建议您使用 grep 函数来过滤全部三个数组中都存在.
Since you are using jQuery I will suggest use grep function to filter the value that are present in all three array.
var a = [1, 2, 3]
var b = [2, 4, 5]
var c = [2, 3, 6]
var result = $.grep(a, function(value, index) {
return b.indexOf(value) > -1 && c.indexOf(value) > -1;
})
console.log(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
说明:循环遍历任何数组并滤除其他数组中存在的值.
Explanation: Loop over any array and filter out the values that are present in other array.
更新(用于多维阵列):
概念-将将[[1,2,3,4]转换为[1,2,3,4]的多维数组展平,然后使用与一维数组相同的逻辑.
Concept - flatten the multidimensional array that is transform [[1,2],3,4] to [1,2,3,4] and then use the same logic used for single dimensional array.
示例:
var a = [
[1, 4], 2, 3
]
var b = [2, 4, 5]
var c = [2, 3, 6, [4, 7]]
//flatten the array's
//[1,4,2,3]
var aFlattened = $.map(a, function(n) {
return n;
})
//[2,4,5]
var bFlattened = $.map(b, function(n) {
return n;
})
//[2,3,6,4,7]
var cFlattened = $.map(c, function(n) {
return n;
})
var result = $.grep(aFlattened, function(value) {
return (bFlattened.indexOf(value) > -1 && cFlattened.indexOf(value) > -1);
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这篇关于JavaScript中的多数组交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!