首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >javascript中数组交集的最简单代码

javascript中数组交集的最简单代码
EN

Stack Overflow用户
提问于 2009-12-11 11:04:05
回答 28查看 567.4K关注 0票数 838

在javascript中实现数组交集的最简单、无库的代码是什么?我想写

代码语言:javascript
复制
intersection([1,2,3], [2,3,4,5])

并获取

代码语言:javascript
复制
[2, 3]
EN

回答 28

Stack Overflow用户

回答已采纳

发布于 2009-12-11 11:08:37

结合使用Array.prototype.filterArray.prototype.includes

代码语言:javascript
复制
const filteredArray = array1.filter(value => array2.includes(value));

对于较旧的浏览器,使用Array.prototype.indexOf但不使用箭头函数:

代码语言:javascript
复制
var filteredArray = array1.filter(function(n) {
    return array2.indexOf(n) !== -1;
});

注意!.includes.indexOf都通过使用===在内部比较数组中的元素,因此如果数组包含对象,它将只比较对象引用(而不是其内容)。如果要指定自己的比较逻辑,请改用Array.prototype.some

票数 1.5K
EN

Stack Overflow用户

发布于 2009-12-11 11:45:01

破坏性似乎是最简单的,特别是如果我们可以假设输入是排序的:

代码语言:javascript
复制
/* destructively finds the intersection of 
 * two arrays in a simple fashion.  
 *
 * PARAMS
 *  a - first array, must already be sorted
 *  b - second array, must already be sorted
 *
 * NOTES
 *  State of input arrays is undefined when
 *  the function returns.  They should be 
 *  (prolly) be dumped.
 *
 *  Should have O(n) operations, where n is 
 *    n = MIN(a.length, b.length)
 */
function intersection_destructive(a, b)
{
  var result = [];
  while( a.length > 0 && b.length > 0 )
  {  
     if      (a[0] < b[0] ){ a.shift(); }
     else if (a[0] > b[0] ){ b.shift(); }
     else /* they're equal */
     {
       result.push(a.shift());
       b.shift();
     }
  }

  return result;
}

非破坏性必须更加复杂,因为我们必须跟踪指数:

代码语言:javascript
复制
/* finds the intersection of 
 * two arrays in a simple fashion.  
 *
 * PARAMS
 *  a - first array, must already be sorted
 *  b - second array, must already be sorted
 *
 * NOTES
 *
 *  Should have O(n) operations, where n is 
 *    n = MIN(a.length(), b.length())
 */
function intersect_safe(a, b)
{
  var ai=0, bi=0;
  var result = [];

  while( ai < a.length && bi < b.length )
  {
     if      (a[ai] < b[bi] ){ ai++; }
     else if (a[ai] > b[bi] ){ bi++; }
     else /* they're equal */
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  return result;
}
票数 158
EN

Stack Overflow用户

发布于 2016-05-05 11:21:27

如果您的环境支持ECMAScript 6 Set,一种简单而有效的方法(请参阅规范链接):

代码语言:javascript
复制
function intersect(a, b) {
  var setA = new Set(a);
  var setB = new Set(b);
  var intersection = new Set([...setA].filter(x => setB.has(x)));
  return Array.from(intersection);
}

较短,但可读性较差(也不会创建额外的交叉点Set):

代码语言:javascript
复制
function intersect(a, b) {
  var setB = new Set(b);
  return [...new Set(a)].filter(x => setB.has(x));
}

请注意,当使用集合时,您将只获得不同的值,因此new Set([1, 2, 3, 3]).size的计算结果为3

票数 101
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1885557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档