admin管理员组文章数量:1390547
I'm a bit more familiar with python, so what is the javascript equivalent of:
In [25]: listA = [1,2,3,4,5,1,1]
In [26]: listB = [1,2]
In [27]: intersect = [element for element in listA if element in listB]
In [28]: intersect
Out[28]: [1, 2, 1, 1]
This is the closest I can get:
var arrA = [1,1,3,4,5,5,6];
var arrB = [1,5];
var arrC = [];
$.each(arrA, function(i,d){ if (arrB.indexOf(d)> -1){arrC.push(d);} ;});
Any ments on preferred methods? I saw this answer, but it was not exactly what I wanted to answer.
I'm a bit more familiar with python, so what is the javascript equivalent of:
In [25]: listA = [1,2,3,4,5,1,1]
In [26]: listB = [1,2]
In [27]: intersect = [element for element in listA if element in listB]
In [28]: intersect
Out[28]: [1, 2, 1, 1]
This is the closest I can get:
var arrA = [1,1,3,4,5,5,6];
var arrB = [1,5];
var arrC = [];
$.each(arrA, function(i,d){ if (arrB.indexOf(d)> -1){arrC.push(d);} ;});
Any ments on preferred methods? I saw this answer, but it was not exactly what I wanted to answer.
Share Improve this question edited May 23, 2017 at 12:24 CommunityBot 11 silver badge asked Mar 11, 2013 at 7:20 gusgus 4071 gold badge5 silver badges17 bronze badges 3- 1 this one does seem to work, so what the question is? – Igor Dymov Commented Mar 11, 2013 at 7:23
- I'm new to javascript, just thought I'd see what people have to say. – gus Commented Mar 11, 2013 at 7:35
-
If it works and you want to know whether there's something better, you're better off at codereview.stackexchange.. Also, this isn't "pure" JavaScript (
$.each
is from the jQuery library). If you're new to JavaScript don't use jQuery at first. First get used to the language and see what isn't possible in JavaScript, then start to use a library to get rid of the limitations. – Zeta Commented Mar 11, 2013 at 7:39
1 Answer
Reset to default 8You could use Array.filter
like this:
var aa = [1,2,3,4,5,1,1]
,ab = [1,2]
,ac = aa.filter(function(a){return ~this.indexOf(a);},ab);
//=> ac is now [1,2,1,1]
Or as extension for Array.prototype
Array.prototype.intersect = function(arr){
return this.filter(function(a){return ~this.indexOf(a);},arr);
}
// usage
[1,2,3,4,5,1,1].intersect([1,2]); //=> [1,2,1,1]
See MDN for the Array.filter
method (also contains a shim for older browsers)
本文标签: javascriptFilter one array of elements using another arrayStack Overflow
版权声明:本文标题:javascript - Filter one array of elements using another array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744680619a2619382.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论