javascript中数组交集的最简单代码在javascript中实现数组交叉的最简单,无库的代码是什么?我想写intersection([1,2,3], [2,3,4,5])得到[2, 3]
3 回答
收到一只叮咚
TA贡献1821条经验 获得超4个赞
使用的组合Array.prototype.filter
和Array.prototype.indexOf
:
array1.filter(value => -1 !== array2.indexOf(value))
或者正如vrugtehagel在评论中所建议的那样,你可以使用更新的更Array.prototype.includes
简单的代码:
array1.filter(value => array2.includes(value))
对于旧浏览器:
array1.filter(function(n) { return array2.indexOf(n) !== -1;});
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
破坏性似乎最简单,特别是如果我们可以假设输入已排序:
/* 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;}
非破坏性必须是一个更复杂的头发,因为我们必须跟踪索引:
/* 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;}
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
如果您的环境支持ECMAScript 6 Set,那么一种简单且有效的(参见规范链接)方式:
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
):
function intersect(a, b) { return [...new Set(a)].filter(x => new Set(b).has(x));}
避免新Set
的b
每次:
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
。
添加回答
举报
0/150
提交
取消