Reputation: 4214
I have two arrays like so;
arr1 = ["foo.com", "bar.com"],
arr2 = ["//test.net/index.html", "http://www.bar.com", "https://foo.com/example.js"]
I'm iterating through arr2
and I want to omit the ones that contain any value of arr1
.
Currently I'm using indexOf
but that doesn't work if the values don't match exactly.
$.each(arr2, function(k,v){
if(arr1.indexOf(v) == -1)
console.log(v);
});
I'd hope for the above code to output
//test.net/index.html
since it's the only value of arr2
that doesn't contain any value of arr1
. What am I doing wrong?
Upvotes: 1
Views: 356
Reputation: 13
Try use the javascript RegExp to do the matching for each array element
http://www.w3schools.com/js/js_regexp.asp
Upvotes: -2
Reputation: 93
I would wrote two each loops for this:
arr1 = ["foo.com", "bar.com"],
arr2 = ["//test.net/index.html", "http://www.bar.com", "https://foo.com/example.js"]
$.each(arr2, function(x,y){
var found = false;
$.each(arr1, function(k,v){
if(!(y.indexOf(v) == -1)){
found = true;
return false;
}
});
if(!found){
console.log(y);
}
found= false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
Upvotes: 3
Reputation: 590
It seems That you're using the Array version of indexOf, which doesn't work id the match is not exact. With a little bit more setup, you can use the String version of indexOf
function compareValues (arr1, arr2){
var res = false;
$.each(arr2, function(k,v) {
checkAgainstArray(arr1, v);
});
function checkAgainstArray(arr1, value) {
$.each(arr1, function(k, v) {
if(value.indexOf(v) !== -1){
res = true;
}
});
}
return res;
}
//later on
var isValueInArray = compareValues(arr1, arr2);
(the code is not tested), but I Hope this helps
Upvotes: 0
Reputation: 193251
You can use filter + some ES5 Array methods:
var arr1 = ["foo.com", "bar.com"],
arr2 = ["//test.net/index.html", "http://www.bar.com", "https://foo.com/example.js"];
var result = arr2.filter(function(val) {
return !arr1.some(function(el) {
return val.indexOf(el) !== -1;
});
});
alert(result);
Support for ES5 starts from IE9+, but if you need it to work in older IE, you can use polyfills (see links I provided), or it's pretty trivial to rewrite some
part with simple for
loop and use $.grep
instead of Array.prototyp.filter
.
Upvotes: 3