简体   繁体   English

javascript检查另一个数组中是否包含1个数组的元素

[英]javascript check existence of elements of 1 array inside the other

For searching elements of one array inside the other, one may use the indexOf() on the target of search and run a loop on the other array elements and in each step check existence. 为了在另一个数组中搜索一个数组的元素,可以在搜索目标上使用indexOf()并在其他数组元素上运行循环,并在每个步骤中检查是否存在。 This is trivial and my knowledge on Javascript is too. 这很简单,我对Javascript的了解也很简单。 Could any one please suggest a more efficient way? 有人可以建议一种更有效的方法吗? Maybe even a built-in method of the language could help? 甚至一种内置的语言方法也可能会有所帮助? Although I couldn't hit to such a method using google. 虽然我无法使用谷歌找到这样的方法。

You can use Array.filter() internally and implement a function on Array's prototype which returns elements which are common to both. 您可以在内部使用Array.filter()并在Array的原型上实现一个函数,该函数返回两者共同的元素。

 Array.prototype.common = function(a) { return this.filter(function(i) { return a.indexOf(i) >= 0; }); }; alert([1,2,3,4,5].common([4,5,6])); // "4, 5" 

Again as you mention in your post, this logic also works by taking each element and checking whether it exists in the other. 就像您在帖子中提到的那样,此逻辑还可以通过获取每个元素并检查它是否存在于另一个元素中来工作。

A hair more efficient way is convert one of the arrays into a hash table and then loop through the second one, checking the presence of elements at O(1) time: 一种更有效的方法是将数组之一转换为哈希表,然后遍历第二个数组,并在O(1)时间检查元素的存在:

 a = [1,2,3,4,5] b = [1,7,3,8,5] map = {} a.forEach(function(x) { map[x] = 1 }) intersection = b.filter(function(x) { return map[x] === 1 }) document.write(JSON.stringify(intersection)) 

This only works if elements in question are primitives. 仅当所讨论的元素是基元时,此方法才有效。 For arrays of objects you have to resort to the indexOf method. 对于对象数组,您必须求助于indexOf方法。

ES6 ("Harmony") does support Set , but strangely not set operations (union, intersection etc), so these should be coded by hand: ES6(“ Harmony”)确实支持Set ,但奇怪的是不支持set操作(联合,交集等),因此应手工编写以下代码:

 // Firefox only a = [1,2,3,4,5] b = [1,7,3,8,5] sa = new Set(a) sb = new Set(b) sa.forEach(function(x) { if (!sb.has(x)) sa.delete(x); }); document.write(uneval([...sa])) 

JavaScript's arrays don't have a method that does intersections. JavaScript的数组没有相交的方法。 Various libraries provide methods to do it (by looping the array as you describe), including Underscore and PrototypeJS (and others, I'm sure). 各种库提供了执行此操作的方法(通过按您所描述的那样循环数组),包括UnderscorePrototypeJS (我敢肯定还有其他方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM