在 javascript 中实现数组交集的最简单、无库的代码是什么?我想写
intersection([1,2,3], [2,3,4,5])
并得到
[2, 3]
原文由 Peter 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 javascript 中实现数组交集的最简单、无库的代码是什么?我想写
intersection([1,2,3], [2,3,4,5])
并得到
[2, 3]
原文由 Peter 发布,翻译遵循 CC BY-SA 4.0 许可协议
破坏性似乎最简单,特别是如果我们可以假设输入已排序:
/* 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;
}
原文由 atk 发布,翻译遵循 CC BY-SA 3.0 许可协议
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
使用
Array.prototype.filter
和Array.prototype.includes
的组合:对于较旧的浏览器,使用
Array.prototype.indexOf
并且没有箭头函数:注意!
.includes
和.indexOf
都使用===
在内部比较数组中的元素,因此如果数组包含对象,它将仅比较对象引用(而不是它们的内容)。如果要指定自己的比较逻辑,请改用Array.prototype.some
。