[英]How to remove set of item values of array from another array in Javascript
var myFind_collections =[3,6,10,234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
var pgRangeCollection = [234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
for(v=0;v<=pgRangeCollection.length;v++){
var pgMatch = pgRangeCollection[v];
clear_pg_range(pgMatch);
}
function clear_pg_range(pgMatch){
//for(d=0;d<=myFind_collections.length-1;d++){
for(d=0;d<=myFind_collections.length-1;d++){
var docFound = parseInt(myFind_collections[d]);
if(pgMatch===docFound){
myFind_collections.splice(myFind_collections[d],1);
alert(docFound + " was removed");
}
}
}
alert(myFind_collections.length);
在上面的代码中,我想删除myFind_collections中等于pgRangeCollection的每个项目
我希望输出为(3,6,10)但我得到的输出为(248,249,250)
我不知道我在哪里犯错,有人可以为此建议解决方案,
提前致谢
使用Array.filter
var myFind_collections =[3,6,10,234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
var pgRangeCollection = [234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
var filtered = myFind_collections.filter(
function(a){return pgRangeCollection.indexOf(a) < 0}
); // => [ 3, 6, 10 ]
答案应该使用KooiInc已经提出的.filter方法,但是由于IE是必需条件,因此我将使用Lodash或Underscore的差分方法:
_.difference(myFind_collections, pgRangeCollection) // [3,6,10]
只需通过CDN包含它即可: http ://cdnjs.com/libraries/lodash.js/
或者如果您已经有了jQuery:
$(myFind_collections).not(pgRangeCollection).get() // [3,6,10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.