jQuery jquery函数通过相同的元素将数组相交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17805268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:59:54 来源:igfitidea点击:
jquery function to intersect arrays by the same elements
提问by IgorCh
Does exists a JS or jQuery function to intersect 2 arrays, for example:
是否存在将 2 个数组相交的 JS 或 jQuery 函数,例如:
var array1 = [1,2,3,4,5];
var array2 = [2,4,8,9,0];
var result = someFun(array1, array2);
//result = [2,4];
sure I can make it manually, but maybe exists a shorter way.
当然我可以手动制作,但可能存在更短的方法。
回答by mishik
Since you have jQuery tag:
因为你有 jQuery 标签:
$(array1).filter(array2);
Or:
或者:
$.map(array1, function(el){
return $.inArray(el, array2) < 0 ? null : el;
})
Or (not for IE8 or less):
或(不适用于 IE8 或更低版本):
array1.filter(function(el) {
return array2.indexOf(el) != -1
});
Example:
例子:
> array1 = [1,2,3,4,5];
[1, 2, 3, 4, 5]
> array2 = [2,4,8,9,0];
[2, 4, 8, 9, 0]
> array1.filter(function(el) {
return array2.indexOf(el) != -1
});
[2, 4]